Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save leonardreidy/fdb22aa88cfb82a54f65d1820c6172b9 to your computer and use it in GitHub Desktop.
Save leonardreidy/fdb22aa88cfb82a54f65d1820c6172b9 to your computer and use it in GitHub Desktop.
// Implement Redux createStore function from scratch,
// with annotations
// Code by Dan Abramov, notes by my good self
const createStore = (reducer) => {
// declare a variable for state
// confined in scope to the block,
// statement or expression in which it
// is used
// store holds current state here
let state;
// because subscribe is called many times,
// we need to be able to keep track of all
// listeners, this array stores them
let listeners = [];
// return current state
const getState = () => state;
// this is the only way to change the internal
// state of the store
// in order to calculate the new state we call
// the given reducer, with the current state
// and the action being dispatched
const dispatch = (action) => {
state = reducer(state, action);
// after the state is updated notify
// all listeners subscribed by calling them
listeners.forEach(listener => listener());
};
// when subscribe is called, we push the given
// listener into the listeners array
const subscribe = (listener) => {
listeners.push(listener);
// return an unsubscribe function which removes
// the given listener from the listener array
return () => {
listeners = listeners.filter(l => l !== listener);
};
};
// populate initial state before returning store
// with a dummy 'action'
dispatch({});
// return store object
return { getState, dispatch, subscribe };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment