Created
May 29, 2017 20:07
-
-
Save orodio/16347b50195597eaf791a4e7b8c13282 to your computer and use it in GitHub Desktop.
redux'ish thing with generators and adhoc handlers
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
const createStore = (state) => { | |
const noop_handler = state => state | |
state = state || {} | |
var handlers = {} | |
var subs = [] | |
const store = (function * () { | |
while (true) { | |
const { type, payload } = yield null | |
state = (handlers[type] || noop_handler)(state, ...payload) | |
subs.forEach(fn => fn(state)) | |
} | |
})() | |
const dispatch = (type, ...payload) => | |
(store.next({ type, payload }), [type, ...payload]) | |
const getState = () => state | |
const handler = (type, fn) => handlers[type] = fn | |
const subscribe = fn => { | |
subs.push(fn) | |
fn(state) // emit after we register so subscriptions are primed | |
return () => subs.splice(subs.indexOf(fn), 1) | |
} | |
dispatch('@@init|0') // force past yield null so we can pass to next | |
dispatch('@@init|1') // initialize state | |
return { | |
dispatch, | |
getState, | |
handler, | |
subscribe, | |
} | |
} | |
const { dispatch, getState, handler, subscribe } = createStore({ foo:"bar" }) | |
subscribe(d => console.log(d)) // will emit right away | |
handler('a', $$$ => ({ ...$$$, foo:"baz" })) | |
handler('b', $$$ => ({ ...$$$, foo:"bar" })) | |
dispatch("a") | |
dispatch("b") | |
dispatch("c") // does nothing | |
handler('c', $$$ => ({ ...$$$, foo:"omg" })) | |
dispatch("c") // does something |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment