Last active
November 8, 2017 20:25
-
-
Save Adrian2112/daefba702dd4ba42a45f4d6e90264e61 to your computer and use it in GitHub Desktop.
js generators sample
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
// based on redux-saga api | |
const select = (fn) => ( { type: 'select', fn: fn } ) | |
const put = (action) => ( { type: 'put', action: action } ) | |
const call = (fn, ...args) => ( { type: 'call', fn: fn, args: args } ) | |
function callSaga(iterator) { | |
let ret; | |
ret = iterator.next(); | |
while(!ret.done) { | |
var nextVal = callFn(ret.value); | |
ret = iterator.next(nextVal); | |
} | |
} | |
function callFn(fnObj) { | |
const type = fnObj.type; | |
if(type === 'select') { | |
return fnObj.fn(getState()); | |
} else if (type === 'put'){ | |
return dispatch(fnObj.action); | |
} else if (type === 'call') { | |
return fnObj.fn(...fnObj.args); | |
} | |
} | |
function getState() { | |
return { | |
a: 1, | |
b: 2 | |
} | |
} | |
function dispatch(action) { | |
console.log(action) | |
} | |
/// saga | |
const fromState = v => state => state[v] | |
const getRandom = () => Math.floor(Math.random() * 10); | |
function* saga() { | |
const a = yield select(fromState('a')); | |
const b = yield select(fromState('b')); | |
yield put({ type: 'UPDATE_A', value: a+b }); | |
const newB = yield call(getRandom); | |
yield put({ type: 'UPDATE_B', value: newB }) | |
yield call(console.log, a+b, newB); | |
} | |
i=saga(); | |
callSaga(i); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment