JavaScript 算法 1_3 生成器函数实现迭代功能

JavaScript 算法 1_3 生成器函数实现迭代功能

以算法 1_1 为例


类定义

// 类定义
class Stack{
  constructor() {
    // 栈顶元素, 包括 next 和 ele
    this.first = null;
    this.count = 0;
  }
  isEmpty(){
    return this.count === 0;
  }
  size(){
    return this.count;
  }
  push(item){
    let oldFirst = this.first;
    let next = {};
    Object.assign(next, {ele: null, next: null});
    next.ele = item;
    this.first = next;
    this.first.next = oldFirst;
    this.count++;
  }
  pop(){
    let top = this.first.ele;
    this.first = this.first.next;
    this.count--;
    return top;
  }
  // 注意这个位置
  *[Symbol.iterator](){
    let index = this.first;
    while (!!index){
      yield index;
      index = index.next;
    }
  }
}

注意最后一个函数 *[Symbol.iterator], 这个函数实现了默认迭代器的功能, * 是generator 函数声明

有了这个函数后, 该类可以使用 for of , ..., 等遍历每一个节点


使用方式

const stack = new Stack();

stack.push(20);
// console.log(stack);
stack.push('小歪');
stack.push([20, 30]);
stack.push({name: '张三'});

for(let item of stack){
  console.log(item);
}
/*
{
  ele: { name: '张三' },
  next: { ele: [ 20, 30 ], next: { ele: '小歪', next: [Object] } }
}
{ ele: [ 20, 30 ], next: { ele: '小歪', next: { ele: 20, next: null } } }
{ ele: '小歪', next: { ele: 20, next: null } }
{ ele: 20, next: null }
*/

之后遍历内容就十分的简单了

原文地址:https://www.cnblogs.com/xiaxiangx/p/14276936.html