Skip to content

Instantly share code, notes, and snippets.

@renanpvaz
Created March 4, 2020 14:30
Show Gist options
  • Save renanpvaz/32b01e466b504756a7889721871ee702 to your computer and use it in GitHub Desktop.
Save renanpvaz/32b01e466b504756a7889721871ee702 to your computer and use it in GitHub Desktop.
export type Effect = { type: string; value?: any }
export type State<T> = T
const get: Effect = { type: 'GET' }
const put = (value: any): Effect => ({ type: 'PUT', value })
const runState = <T>(
genFn: () => Generator<Effect, void, State<T>>,
initialState: State<T>,
) => {
const gen = genFn()
let state = { ...initialState }
let curr = gen.next()
while (!curr.done) {
switch (curr.value.type) {
case 'GET':
curr = gen.next(state)
break
case 'PUT':
state = curr.value.value
curr = gen.next()
break
}
}
}
function* increment() {
const state = yield get
yield put(state + 1)
}
runState(increment, 0)
export { runState, get, put }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment