Last active
November 3, 2020 14:53
-
-
Save esco/eb224ac20dcc6721f6d0b663d3fbe6b1 to your computer and use it in GitHub Desktop.
Simple Redux Store
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
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