Build a Redux-Style Store

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write createStore(reducer, initialState), returning an object with getState, dispatch and subscribe. getState() returns the current state, which is initialState itself until the first dispatch (don't call the reducer before then). dispatch(action) throws a TypeError unless action is an object with a type property; otherwise it sets the state to reducer(state, action), then calls every subscribed listener with no arguments, in the order they subscribed, and returns action. If the reducer throws, the error passes on to the caller and the state and listeners are left as they were. A reducer calling dispatch throws an Error with the message "Reducers may not dispatch actions.". subscribe(listener) returns an unsubscribe function, which is safe to call more than once. The listeners a dispatch calls are fixed before it calls them: subscribing or unsubscribing during a dispatch only counts from the next one.

Your code must pass

  • Starts with the initial state and updates it on dispatch
  • Throws a TypeError for an action without a type
  • Calls subscribers after each dispatch until they unsubscribe
  • Subscribing or unsubscribing during a dispatch waits for the next one
  • Reducers can't dispatch
  • A reducer that throws leaves the store usable