Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.


ES6 Iterators and Generators

node v0.12.18
version: 1.0.0
ES6 introduced the new for...of construct to iterate over collections:
// For...of will give us the items instead of the indexes. for (var item of [2,4,6,8]) console.log(item)
With iterators, your own custom collections can define how they behave in for...of. Simply assign an iterator method to a property with the global iterator symbol:
var cart = { items: ["pizza", "car", "pastrami"], [Symbol.iterator] : function () { var index = 0; var length = this.items.length; return { next: () => { if (index < length) return { value: this.items[index++], done: false }; return { value:null, done: true }; } } } } for (item of cart) console.log(item + " is in your cart!");
Generators allow you to write the same code in a much less verbose way:
var cart = { items: ["pizza", "car", "pastrami"], [Symbol.iterator] : function* () { for (var index = 0; index < this.items.length; ++index) yield this.items[index]; } } for (item of cart) console.log(item + " is in your cart!");
Learn more about iterators here: https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/ Leran more about generators here: https://hacks.mozilla.org/2015/05/es6-in-depth-generators/

1 comment

  • posted 6 months ago by 6473519fc0a4050008c8cf99
    اگر میشود کیف پول را همیشه ذخیره داشته باشیم

sign in to comment