Skip to content

Instantly share code, notes, and snippets.

@esco
Last active November 3, 2020 14:53
Show Gist options
  • Save esco/eb224ac20dcc6721f6d0b663d3fbe6b1 to your computer and use it in GitHub Desktop.
Save esco/eb224ac20dcc6721f6d0b663d3fbe6b1 to your computer and use it in GitHub Desktop.
Simple Redux Store
function createStore(reducer, preloadedState) {
let state = preloadedState
const idPool = [0]
const listeners = new Map()
function getState() {
return state
}
function subscribe(listener) {
let id = idPool.pop()
if (!idPool.length) {
idPool.push(id + 1)
}
listeners.set(id, listener)
return function unsubscribe() {
listeners.delete(id)
idPool.push(id)
}
}
function dispatch(action) {
state = reducer(state, action)
for ([_, listener] of listeners) {
listener()
}
}
dispatch({ type: '@@redux/INIT' })
return { dispatch, subscribe, getState }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment