Skip to content

Instantly share code, notes, and snippets.

@orodio
Created May 31, 2017 21:28
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/8380d84af90b688b73466132390c05f0 to your computer and use it in GitHub Desktop.
Save orodio/8380d84af90b688b73466132390c05f0 to your computer and use it in GitHub Desktop.
redux with a generator
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