Skip to content

Commit

Permalink
refactor(ui/store): FavolinkStore class 내부 emitChange 제거, listeners 배…
Browse files Browse the repository at this point in the history
…열에서 Set으로 변경 (#320)
  • Loading branch information
sukvvon authored Aug 20, 2024
1 parent 3f0af94 commit f5e6ba4
Showing 1 changed file with 10 additions and 14 deletions.
24 changes: 10 additions & 14 deletions packages/ui/src/store/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ export interface FavolinkStoreObserver<T> {
getState: () => T;
setState: (next: SetStateAction<T>) => void;
subscribe: (listener: () => void) => () => void;
emitChange: () => void;
}

type SetStateFn<T> = (prevState: T) => T;
Expand All @@ -11,10 +10,11 @@ type SetStateAction<T> = SetStateFn<T> | T;

export class FavolinkStore<T> implements FavolinkStoreObserver<T> {
private state: T;
private listeners: (() => void)[] = [];
private listeners: Set<() => void>;

constructor(initialState: T) {
this.state = initialState;
this.listeners = new Set();
}

getState = () => {
Expand All @@ -23,29 +23,25 @@ export class FavolinkStore<T> implements FavolinkStoreObserver<T> {

setState = (next: SetStateAction<T>) => {
const setter = next as SetStateFn<T>;
const nextValue = typeof next === 'function' ? setter(this.state) : next;
const nextState = typeof next === 'function' ? setter(this.state) : next;

if (this.state === nextValue) {
if (this.state === nextState) {
return;
}

this.state = nextValue;
this.emitChange();
this.state = nextState;
this.listeners.forEach((listener) => {
listener();
});
};

subscribe = (listener: () => void) => {
this.listeners = [...this.listeners, listener];
this.listeners.add(listener);

return () => {
this.listeners = this.listeners.filter((l) => l !== listener);
this.listeners.delete(listener);
};
};

emitChange = () => {
this.listeners.forEach((listener) => {
listener();
});
};
}

export function createFavolinkStore<T>(initialState: T) {
Expand Down

0 comments on commit f5e6ba4

Please sign in to comment.