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;
        }
      }
  • 相关阅读:
    “爆奇葩”项目之索引页
    android 的生命周期自我理解
    Jquery Mobile 中文API站
    根据两点经纬度计算距离
    sql语句查询经纬度范围
    Asp.net core 笔记
    Docker 笔记
    IOC和DI
    PHP学习笔记十、图像处理
    PHP学习笔记九、cookie与session
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11308356.html
Copyright © 2011-2022 走看看