Skip to content

Instantly share code, notes, and snippets.

@sbrl
Created June 2, 2015 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbrl/98cd9bde4d06da5ad5ec to your computer and use it in GitHub Desktop.
Save sbrl/98cd9bde4d06da5ad5ec to your computer and use it in GitHub Desktop.
ES6 Generators 1 Source Code used in a blog post.
function *first_test()
{
yield "Hello!";
yield "I am a generator!";
yield "This is the last thing I will yield.";
}
var test = first_test(),
next = test.next();
do {
console.log(next.value);
next = test.next();
} while(!next.done);
console.log("****");
for(var result of first_test())
{
console.log(result);
}
/* Source code used in the production of the first ES6 generators post on my blog.
* Written by Starbeamrainbowlabs
* Website: https://starbeamrainbowlabs.com/
* Blog: https://starbeamrainbowlabs.com/blog/
* Twitter: @SBRLabs
* Reddit: /u/Starbeamrainbowlabs
*/
function *get_id(start)
{
var current = start;
while(true)
{
yield start.toString(16);
start++;
}
}
var readline = require("readline"),
interface = readline.createInterface({
input: process.stdin,
output: process.stdout,
}),
id_generator = get_id(404);
interface.setPrompt("> ");
interface.on("line", function(line) {
var words = line.split(/\s+/gi);
interface.write(`next id: ${id_generator.next().value}`);
});
"use strict";
function *counter(base)
{
var number = base;
while(true)
{
number += yield number;
}
}
var generator = counter(100);
for(var i = 0; i < 10; i++)
{
let next = generator.next(Math.floor(Math.random() * 10))
console.log(next.value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment