Created
March 4, 2020 14:30
-
-
Save renanpvaz/32b01e466b504756a7889721871ee702 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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