-
-
Save RickWong/c85a7466c33a39eb0e645a21b4230520 to your computer and use it in GitHub Desktop.
Redux in <1kb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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