zoukankan      html  css  js  c++  java
  • 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 }
    */
    

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

  • 相关阅读:
    Tsar 服务器系统和应用信息的采集报告工具
    mysqltuner
    MySQL性能监控工具-MONyog
    tuning-primer.sh mysql 报表
    mytop
    InnoTop
    mysql监控管理工具--innotop
    iotop,pt-ioprofile : mysql IO负载高的来源定位
    PERCONA-TOOLKIT 工具的安装与使用2
    PERCONA-TOOLKIT : pt-ioprofile分析IO情况
  • 原文地址:https://www.cnblogs.com/xiaxiangx/p/14276936.html
Copyright © 2011-2022 走看看