mediumcodingjavascript~15 min
Private State Store with Closures
Objective: Encapsulate state and expose controlled mutation, with defensive copies and subscriptions.
Build a tiny observable store whose state can only be changed through its API.
- createStore(initial) returns { getState, setState, subscribe }.
- setState accepts a partial object or an updater function (state) => partial, and shallow-merges it.
- getState returns a copy; mutating it must not change the store.
- subscribe(listener) calls listener(newState) after each setState and returns an unsubscribe function.
JavaScript
⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor
Output
> Nothing has run yet.
Interview follow-up questions
- Why shallow-copy instead of deep-copy here, and when would that bite?
- How would you avoid notifying when nothing changed?
- How does this relate to Redux or Zustand's design?