Implement createStore(reducer, initialState), a tiny version of a Redux store. A reducer is a function (state, action) => newState that computes the next state from the current one and an action object.
The store has three methods:
getState()returns the current state.dispatch(action)sets the state toreducer(currentState, action). Then it calls every listener with no arguments and returnsaction.subscribe(listener)registers a listener and returns anunsubscribefunction.
Rules for listeners:
- They run after the state has been updated, in the order they subscribed.
- Subscribing the same function twice registers it twice. Each
unsubscriberemoves only its own registration, and calling it again does nothing. - If a listener subscribes or unsubscribes during a dispatch, the change applies from the next dispatch. The current dispatch calls exactly the listeners that were registered when it started.
Input: const s = createStore(counter, { count: 0 });
s.dispatch({ type: 'add', amount: 5 });
s.getState()
Output: { count: 5 }
Input: const stop = s.subscribe(log); s.dispatch(a); stop(); s.dispatch(b);
Output: log is called once