Skip to content
Onsite

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 as reducer(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 an unsubscribe function. Calling unsubscribe twice 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

Run checks the 3 visible tests, Submit all 10.