Created
May 31, 2017 21:28
-
-
Save orodio/8380d84af90b688b73466132390c05f0 to your computer and use it in GitHub Desktop.
redux with a generator
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
export const createStore = (reducer, state = {}) => { | |
let subs = [] | |
const store = (function * () { | |
while (true) { | |
const event = yield null | |
state = reducer(state, event) | |
subs.forEach(fn => fn(state)) | |
} | |
}) | |
// prime generator | |
store.next({ type:"@@init|0" }) | |
store.next({ type:"@@init|1" }) | |
const getState = () => state | |
const dispatch = ev => store.next(ev) | |
const subscribe = fn => { | |
subs.push(fn) | |
fn(state) | |
unsubbed = false | |
return () => { | |
if (unsubbed) return | |
unsubbed = true | |
subs.splice(subs.indexOf(fn), 1) | |
} | |
} | |
return { getState, dispatch, subscribe } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment