zoukankan      html  css  js  c++  java
  • [Javascript] Write a Generator Function to Generate the Alphabet / Numbers

    When you need to generate a data set, a generator function is often the correct solution. A generator function is defined with function* and then you yield each result you want out of the function when you call it. Generators pair well with the ... operator inside of Array because they serve as iterators which can be called until all their results are exhausted.

    function* generateAlphabet() {
      let i = "a".charCodeAt(0);
      let end = "z".charCodeAt(0) + 1;
    
      while (i < end) {
        yield String.fromCharCode(i);
        i++;
      }
    }
    
    let alphabet = [...generateAlphabet()];
    
    Array.prototype.fill = function* generateNumber(val) {
      let i = 0;
      while (i < Number(this.length)) {
        yield typeof val === "function" ? val(i) : val;
        i++;
      }
    };
    var numbers = [...new Array(6).fill()];
    console.log(numbers); // [undefined, undefined, undefined, undefined, undefined, undefined]
    var numbers = [...new Array(6).fill(0)];
    console.log(numbers); // [0, 0, 0, 0, 0, 0]
    var numbers = [...new Array(6).fill(i => i * 2)];
    console.log(numbers); //[0, 2, 4, 6, 8, 10]
  • 相关阅读:
    Lambda
    Guava
    创建数据库时报错 'str' object has no attribute 'decode'
    服务器并发测试(jmeter)
    Mosquitto 创建用户自动输入密码
    menuconfig 语法与用法
    Django操作mongodb
    mqtt mosquitto 安装与使用
    python 使用mongodb数据库
    djangorestframework token 认证
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10311672.html
Copyright © 2011-2022 走看看