Since generators can take initial values and expose a next method which can run updates on the initial value, it becomes trivial to make a state machine with a generator where you pass your transitions into the next method. This lesson walks through creating a state machine with a generator.
function* stateMachine(initState: number) {
let action;
while (true) {
if (action === 'increase') {
initState++;
}
if (action === 'decrease') {
initState--;
}
action = yield initState;
}
}
let state = stateMachine(0);
console.log(state.next()); // trigger the init state {value: 0, done: false}
console.log(state.next('increase')); // {value: 1, done: false}
console.log(state.next('increase')); // {value: 2, done: false}
console.log(state.next('decrease')); // {value: 1, done: false}
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!