首页 > 编程语言 >[Javascript] Generator with example - 1

[Javascript] Generator with example - 1

时间:2023-05-25 17:44:14浏览次数:39  
标签:node console log Generator Javascript yield let root example

Difference between yieldand return

returnset doneto true

/**
 * Example 1
 */

function* loggerator() {
  console.log("running");
  yield "paused";
  console.log("running again");
  return "stopped";
}

let logger = loggerator();
console.log(logger.next()); // running
// { value: 'paused', done: false }
console.log(logger.next()); // running again
// { value: 'stopped', done: true }

 

Generator are both iterable and iterators

/**
 * Example 2
 */

// generators are both iterable and iterators

function* abc() {
  yield "a";
  yield "b";
  yield "c";
}

for (let letter of abc()) {
  console.log(letter);
}

console.log([...abc()]);

 

Custom iterables with @@iterator

/**
 * Example 3
 */

// custom iterables with @@iterator

const cardDeck = {
  suits: ["♥", "♠", "♣", "♦"],
  court: ["J", "Q", "K", "A"],
  [Symbol.iterator]: function* () {
    for (let suit of this.suits) {
      for (let i = 2; i <= 10; i++) {
        yield `${suit} ${i}`;
      }
      for (let c of this.court) {
        yield `${suit} ${c}`;
      }
    }
  },
};

console.log([...cardDeck]);
/**
 * [
  '♥ 2', '♥ 3', '♥ 4',  '♥ 5',  '♥ 6',  '♥ 7',
  '♥ 8', '♥ 9', '♥ 10', '♥ J',  '♥ Q',  '♥ K',
  '♥ A', '♠ 2', '♠ 3',  '♠ 4',  '♠ 5',  '♠ 6',
  '♠ 7', '♠ 8', '♠ 9',  '♠ 10', '♠ J',  '♠ Q',
  '♠ K', '♠ A', '♣ 2',  '♣ 3',  '♣ 4',  '♣ 5',
  '♣ 6', '♣ 7', '♣ 8',  '♣ 9',  '♣ 10', '♣ J',
  '♣ Q', '♣ K', '♣ A',  '♦ 2',  '♦ 3',  '♦ 4',
  '♦ 5', '♦ 6', '♦ 7',  '♦ 8',  '♦ 9',  '♦ 10',
  '♦ J', '♦ Q', '♦ K',  '♦ A'
]
 */

Another way to write it:

const cardDeck = {
  suits: ["♥", "♠", "♣", "♦"],
  court: ["J", "Q", "K", "A"],
  *[Symbol.iterator]() {
    for (let suit of this.suits) {
      for (let i = 2; i <= 10; i++) {
        yield `${suit} ${i}`;
      }
      for (let c of this.court) {
        yield `${suit} ${c}`;
      }
    }
  },
};

 

Lazy evaluation & infinite sequences

/**
 * Example 4
 */

// lazy evaluation & infinite sequences

function* infiniteAndBeyond() {
  let i = 1;
  while (true) {
    yield i++;
  }
}

function* take(n, iterable) {
  for (let item of iterable) {
    if (n <= 0) return;
    n--;
    yield item;
  }
}

console.log([...take(5, infiniteAndBeyond())]); //[1, 2, 3, 4, 5];

function* map(iterable, mapFn) {
  for (let item of iterable) {
    yield mapFn(item);
  }
}
const inc = (num) => num + 1;
console.log([...map(take(5, infiniteAndBeyond()), inc)]); // [ 2, 3, 4, 5, 6 ]

 

yield*:delegate iteration control to another iterator

/**
 * Example 5
 */

function binaryTreeNode(value) {
  const node = { value };
  node[Symbol.iterator] = function* depthFirst() {
    yield node.value;
    if (node.leftChild) {
      // explainer: yield* is a special syntax that allows us to delegate iteration control to another iterator
      yield* node.leftChild;
    }
    if (node.rightChild) {
      yield* node.rightChild;
    }
  };
  return node;
}

const makeTree = () => {
  const root = binaryTreeNode("root");
  root.leftChild = binaryTreeNode("branch left");
  root.rightChild = binaryTreeNode("branch right");
  root.leftChild.leftChild = binaryTreeNode("leaf L1");
  root.leftChild.rightChild = binaryTreeNode("leaf L2");
  root.rightChild.leftChild = binaryTreeNode("leaf R1");
  return root;
};
const tree = makeTree();

console.log([...tree]);
/**
 * [
  'root',
  'branch left',
  'leaf L1',
  'leaf L2',
  'branch right',
  'leaf R1'
]
 */

 

标签:node,console,log,Generator,Javascript,yield,let,root,example
From: https://www.cnblogs.com/Answer1215/p/17432396.html

相关文章

  • javascript prototype and class
    js中的prototype绝对是js的一个重要知识点,有点像delegate的模式,和oop对象形式还是有些差别的,尽管可以做同样的事情。简要学习可以参见:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes关于js的class和java的语法很像,参见:https://develope......
  • 碎片化学习前端之JavaScript(for...in 和 Object.keys() 的区别)
    前言JavaScript中遍历对象的方式主要有:for...in和Object.keys()两种方式。for...inletobj={name:'ming',age:18,}obj[Symbol('hello')]='world'obj.__proto__={gender:'man',job:'font-end'}f......
  • 一篇文章解密 - 如何在MyEclipse中使用JavaScript编写代码?
    MyEclipsev2022.1.0正式版下载MyEclipse技术交流群:742336981欢迎一起进群讨论JavaScript项目在MyEclipse2021及更高版本中,JavaScript支持对大多数JavaScript源代码都是开箱即用的——不需要特殊的JavaScriptEclipse项目或JavaScriptfacet。但是,我们建议使用jscon......
  • 【JavaScript用法】JavaScript(JS)的基本语法(JS数据类型,JS变量,JS运算符,JS流程控制语句
    JavaScript(JS)的基本语法目录JavaScript(JS)的基本语法一.与html结合方式二.注释三.数据类型:四.变量五.运算符(和Java有点类似)六.流程控制语句(和JAVA 类似):七.JS特殊语法:一.与html结合方式       1.内部JS:定义<script>,标签体内容就是js代码(可以理解为和html......
  • 流程表单JavaScript代码
    ----订单流程-----------//表单加载初始化时functionpreinit(){}//表单加载完成,isrun代表流程是否流转中1-是,0-否functionLoaded(isrun){$("#om_order_status").attr("disabled","disabled");......
  • javascript web api,bom&dom
    Api1.获取dom元素constx=document.querySelector('选择器')querySelectorAll返回的是伪数组2.操作元素内容对象.innerText对象.innerHTML会解析标签3.操作元素样式属性1.style<script>  constdiv=document.querySelector('.box')  box.style.width=......
  • javascript的 this 详解以及apply与call的用法意义及区别
    [color=red][b]关于JavaScript中apply与call的用法意义及区别[/b][/color][url]http://www.cnitblog.com/yemoo/archive/2007/11/30/37070.aspx[/url][color=red][b]JAVASCRIPTTHIS详解[/b][/color]在面向对象编程语言中,对于this关键字我们是非常熟悉的。比如C++、C#和Java等都......
  • #yyds干货盘点#JavaScript的数学对象——Math对象
    Math对象●js给我们提供了一些操作数字的方法●也是一种数据类型是复杂数据类型●Math对象的通用语法:Math.xxx()random()●Math.random()这个方法是用来生成一个0~1之间的随机数●每次执行生成的数字都不一样,但是一定是0~1之间的●生成的数字包含0,但是不包含1var......
  • ahb_system_generator
    0.ahb_system_generatorEnviroment:WSL2ahb_generator要运行AHB系统生成器,必须安装PERL(一般系统自带)和一个名为Tk的GUIPERL模块perl--version //检查perlperl-e"useTk" //检查Tk模块,若未安装会返回错误信息1.perlinstall官网下载Tk模块安装包进入解压......
  • boltdb example
    源码链接:https://github.com/zupzup/boltdb-example.gitpackagemainimport("bytes""encoding/json""fmt""github.com/boltdb/bolt""log""time")//ConfigtypetypeConfig......