Created
June 2, 2015 11:43
-
-
Save sbrl/98cd9bde4d06da5ad5ec to your computer and use it in GitHub Desktop.
ES6 Generators 1 Source Code used in a blog post.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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}`); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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