Created
August 25, 2016 06:24
-
-
Save rstacruz/4fccd5ad5853184c3c9dbfe3f596cf1f 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
var INIT = '@redux/INIT' | |
function createStore (reducer, state, enhancer) { | |
if (enhancer) return enhancer(createStore)(reducer, state) | |
var subscribers = [] | |
dispatch({ type: INIT }) | |
return { | |
subscribe: subscribe, | |
dispatch: dispatch, | |
getState: getState, | |
replaceReducer: replaceReducer | |
} | |
function subscribe (listener) { | |
subscribers.push(listener) | |
var idx = subscribers.length - 1 | |
return function unsubscribe () { | |
delete subscribers[idx] | |
} | |
} | |
function dispatch (action) { | |
state = reducer(state, action) | |
subscribers.forEach(function (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