Skip to content

Instantly share code, notes, and snippets.

@yukeehan
Created December 3, 2018 16:14
Show Gist options
  • Save yukeehan/bdc9d20b38f75e310fe320054418c902 to your computer and use it in GitHub Desktop.
Save yukeehan/bdc9d20b38f75e310fe320054418c902 to your computer and use it in GitHub Desktop.
creatStore from Scratch
const createStore = (reducer) => {
let state;
let listeners = []; // an array of listeners
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener()); // to notify every change listener by calling it
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter (l => l !== listener); // unsubscribe the listener that alredy been fired
};
};
dispatch({}); // initial state populated dummy action
return { getState, dispatch, subscribe }; // 3 main methods of createStore
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment