Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Created August 25, 2016 06:24
Show Gist options
  • Save rstacruz/4fccd5ad5853184c3c9dbfe3f596cf1f to your computer and use it in GitHub Desktop.
Save rstacruz/4fccd5ad5853184c3c9dbfe3f596cf1f to your computer and use it in GitHub Desktop.
Redux in <1kb
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