zoukankan      html  css  js  c++  java
  • [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}
  • 相关阅读:
    内部共享上网
    Harbor部署
    一、Gitlab安装
    Dockerfile
    DockerCompose
    二、Git
    nginx域名代理
    三、jenkins持续集成工具安装
    chrome对于“submit”关键字的保留
    insightface 提取人脸特征(超简洁)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12167505.html
Copyright © 2011-2022 走看看