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;
        }
      }
  • 相关阅读:
    从POJ1958引发对n盘m塔Hanoi问题的思考
    SPOJGSS3 Can you answer these queries III
    【模板】SPFA判负环(洛谷P3385)
    【模板】强联通缩点(洛谷P3387)
    Luogu P2186 小Z的栈函数
    Luogu P2129 小Z的情书
    LGBT学分块
    LGBT玩扫雷
    A 美丽的子树
    B(升降序列)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11308356.html
Copyright © 2011-2022 走看看