CodePark/ problems / Mini Redux store
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Event emitters and observable state

Mini Redux store

easyabout 15 minutes in an interview

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 to reducer(currentState, action). Then it calls every listener with no arguments and returns action.
  • subscribe(listener) registers a listener and returns an unsubscribe function.

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 unsubscribe removes 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