zoukankan      html  css  js  c++  java
  • [Javascript] Convert a forEach method to generator

    For example we have a 'forEach' method which can loop though a linked list:

    forEach(fn) {
        let node = this.head;
        let counter = 0;
        while (node) {
          fn(node, counter);
          node = node.next;
          counter++;
        }
      }

    Test:

    test('applies a transform to each node', () => {
        const l = new List();
    
        l.insertLast(1);
        l.insertLast(2);
        l.insertLast(3);
        l.insertLast(4);
    
        l.forEach(node => {
          node.data += 10;
        });
    
        expect(l.getAt(0).data).toEqual(11);
        expect(l.getAt(1).data).toEqual(12);
        expect(l.getAt(2).data).toEqual(13);
        expect(l.getAt(3).data).toEqual(14);
      });

    What if we want to use for...of loop? Then we need to convert LinkedList to support generator partten, the usage of for..of:

    test('works with the linked list', () => {
        const l = new List();
    
        l.insertLast(1);
        l.insertLast(2);
        l.insertLast(3);
        l.insertLast(4);
    
        for (let node of l) {
          node.data += 10;
        }
    
        expect(l.getAt(0).data).toEqual(11);
        expect(l.getAt(1).data).toEqual(12);
        expect(l.getAt(2).data).toEqual(13);
        expect(l.getAt(3).data).toEqual(14);
      });

    Implementation:

    *[Symbol.iterator]() {
        let node = this.head;
        while (node) {
          yield node;
          node = node.next;
        }
      }
  • 相关阅读:
    DateTime与DateTime?赋值问题以及null类型的如何赋值问题
    ajax请求aspx.cs后台方法
    Windows 下安装 Memcached
    windows下mysql表名区分大小写
    csredis
    路由名称
    发布后的项目打开swagger
    IActionResult的返回类型
    ASP.NET Core开发之HttpContext
    Web SQL数据库
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11308356.html
Copyright © 2011-2022 走看看