Skip to content

Instantly share code, notes, and snippets.

@orodio
Created May 29, 2017 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orodio/16347b50195597eaf791a4e7b8c13282 to your computer and use it in GitHub Desktop.
Save orodio/16347b50195597eaf791a4e7b8c13282 to your computer and use it in GitHub Desktop.
redux'ish thing with generators and adhoc handlers
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