createStore
MediumP2Coding
Implement createStore(reducer, preloadedState), a minimal Redux-style store. It returns an object with three methods:
getState()returns the current state.dispatch(action)computes the next state asreducer(currentState, action), stores it, then calls every subscribed listener (with no arguments), in subscription order. It returns the dispatched action.subscribe(listener)registers a listener and returns anunsubscribefunction. Callingunsubscribetwice is harmless.
When the store is created it runs reducer(preloadedState, { type: '@@INIT' }) once to compute the initial state, so a reducer's default state argument works. The reducer must be pure; do not mutate the state in the store.
A listener that subscribes or unsubscribes while listeners are being notified must not change who is notified in that same dispatch.
Example 1
- Input
- const store = createStore((s = 0, a) => a.type === 'inc' ? s + 1 : s); store.dispatch({ type: 'inc' }); store.getState();
- Output
- 1
Constraints
- Actions are objects with a type property.
- At most 10^4 listeners.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.