[Javascript] Use a Generator Like a Closure

Generators emulate the behavior of a closure where they wrap an initial value then can take subsequent values through next to yield something based on that initial wrapped value. This lesson walks through creating a closure then re-creating the same behavior with a generator.

function makeAdder(x) {
    return function (y) {
        return x + y
    }
}

let add2 = makeAdder(2)

//---- Generator ------
function* makeAdderGen(x: number) {
    let y = yield x;

    // because every time code pause at yield
    // it is safe to use while true
    while (true) {
        // fist doing yield 3 + x
        // .next(2) --> yield 3 + 2
        // puased
        // when .next(4) --> y = 4, console.log('y', 4)
        y = yield y + x;
        console.log('y', y)
    }
}

let add3 = makeAdderGen(3);
console.log(add3.next()); // {value: 3, done: false}
console.log(add3.next(2)); // {value: 5, done: false}
console.log(add3.next(4)); // y 4  {value: 7, done: false}
原文地址:https://www.cnblogs.com/Answer1215/p/12167505.html