Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Created June 11, 2018 18:31
Show Gist options
  • Save sagar-gavhane/8a84275644c8374aef3b6fa9e8c18b46 to your computer and use it in GitHub Desktop.
Save sagar-gavhane/8a84275644c8374aef3b6fa9e8c18b46 to your computer and use it in GitHub Desktop.
// Ref:
// 1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
// 2. https://davidwalsh.name/es6-generators
// ------------------------------------
function makeIterator(array) {
var nextIndex = 0;
return {
next: function() {
return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{done: true};
}
};
}
var it = makeIterator(['yo', 'ya']);
console.log(it.next()); // 'yo'
console.log(it.next()); // 'ya'
console.log(it.next()); // true
// ------------------------------------
function* idMaker() {
var index = 0;
while(true){
yield index++;
}
}
var gen = idMaker();
console.log(gen.next()); // 0
console.log(gen.next()); // 1
console.log(gen.next()); // 2
// ------------------------------------
var myIterable = {};
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
for (let value of myIterable) {
console.log(value);
}
// ------------------------------------
function *foo() {
var x = 1 + (yield "foo");
console.log('x', x);
}
var it = foo();
console.log(it.next());
console.log(it.next(100));
// ------------------------------------
// note: `foo(..)` here is NOT a generator!!
function foo(x) {
console.log("x: " + x);
}
function *bar() {
yield; // just pause
foo( yield ); // pause waiting for a parameter to pass into `foo(..)`
}
var it = bar();
console.log(it.next());
console.log(it.next(100));
// ------------------------------------
function *foo() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}
var it = foo();
console.log('it', it.next());
console.log('it', it.next());
console.log('it', it.next());
console.log('it', it.next());
console.log('it', it.next());
console.log('it', it.next());
// ------------------------------------
function *foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var it = foo( 5 );
// note: not sending anything into `next()` here
console.log( it.next() ); // { value:6, done:false }
console.log( it.next( 12 ) ); // { value:8, done:false }
console.log( it.next( 13 ) ); // { value:42, done:true }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment