Skip to content

Instantly share code, notes, and snippets.

@shiponcs
Created April 25, 2020 14:00
Show Gist options
  • Save shiponcs/be240474b9fe8e0d0cfdf9dfc3fd665d to your computer and use it in GitHub Desktop.
Save shiponcs/be240474b9fe8e0d0cfdf9dfc3fd665d to your computer and use it in GitHub Desktop.
This is the basic implementation (without a few minor details) of createStore function of Redux library
const createStore = (reducer) => {
let state;
let listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach((listener) => listener());
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter((l) => l !== listener);
};
};
dispatch({});
return { getState, dispatch, subscribe };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment