Function * (generator object) practical utility?

This is a new technology that is part of the ECMAScript 2015 (ES6) standard. This technology specification has been completed, but the compatibility table for use and implementation status in various browsers.

A function declaration * (the keyword function followed by an asterisk) defines a generator function that returns a Generator object.

You can also define generator functions using the GeneratorFunction constructor function and function expression.

Example:

function* idMaker(){ var index = 0; while(index < 3) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // undefined // ... 

MDN function *

Question:

Although this example is understandable, why should I use it on something like this:

 var index = 0; function idMaker(){ return (index < 2) ? index++: undefined; } 

or even (to respond to a comment in the index area):

 var idMaker = function(){ this.index = 0; this.next = function(){ var res = (this.index < 3) ? this.index++: undefined; return { value: res }; }; } var gen = new idMaker(); console.log(gen.next().value); console.log(gen.next().value); console.log(gen.next().value); console.log(gen.next().value); 
+5
source share

All Articles