编程语言
首页 > 编程语言> > [Javascript] Create a State Machine with a Generator

[Javascript] Create a State Machine with a Generator

作者:互联网

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}

 

标签:false,Create,Javascript,value,next,Machine,state,initState,console
来源: https://www.cnblogs.com/Answer1215/p/12167593.html