type Listener<T> = (state: T) => void;

export function createStore<T>(initial: T) {
  let state = initial;
  const listeners = new Set<Listener<T>>();

  const getSnapshot = () => state;

  const setState = (next: T) => {
    state = next;
    listeners.forEach((l) => l(state));
  };

  const subscribe = (fn: Listener<T>) => {
    listeners.add(fn);
    return () => {
        listeners.delete(fn);
    }
  };

  return { getSnapshot, setState, subscribe };
}