Skip to content

Instantly share code, notes, and snippets.

@RickWong
Forked from rstacruz/µredux.js
Last active August 25, 2016 10:15
Show Gist options
  • Save RickWong/c85a7466c33a39eb0e645a21b4230520 to your computer and use it in GitHub Desktop.
Save RickWong/c85a7466c33a39eb0e645a21b4230520 to your computer and use it in GitHub Desktop.
Redux in <1kb
const INIT = '@redux/INIT';
export const createStore = (reducer, state, enhancer) => {
if (enhancer) {
return enhancer(createStore)(reducer, state);
}
const subscribers = [];
dispatch({ type: INIT });
return {
subscribe,
dispatch,
getState,
replaceReducer,
};
function subscribe (listener) {
subscribers.push(listener);
const idx = subscribers.length - 1;
return () => { delete subscribers[idx]; };
}
function dispatch (action) {
state = reducer(state, action);
subscribers.forEach(fn => fn());
}
function getState () {
return state;
}
function replaceReducer (next) {
reducer = next;
dispatch({ type: INIT });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment