Skip to content

Instantly share code, notes, and snippets.

@Ij888
Created August 12, 2015 00:15
Show Gist options
  • Save Ij888/0218c533cf672b74810c to your computer and use it in GitHub Desktop.
Save Ij888/0218c533cf672b74810c to your computer and use it in GitHub Desktop.
ES6 Generator
<div class="container">
<h1>ES6 Generator Example</h1>
<p>
Demonstrates iterating an array of function yielding the result for each using a for loop and ES6 Generators.
</p>
<p>
Click "Run Example" below to display the results.
</p>
<pre>
function* gen(){
for(var i=0; i < funcs.length; i++){
yield funcs[i]();
}
}
function run() {
for(f of gen()){
console.log('Result: ' + f);
}
}
</pre>
<p id="results"></p>
<p>
<button type="button" class="btn btn-default" onclick="run();">Run Example</button>
</p>
</div>
var results = document.getElementById('results');
function a (res) {
return 'a';
}
function b (res) {
return 'b';
}
function c (res) {
return 'c';
}
var funcs = [];
funcs.push(a);
funcs.push(b);
funcs.push(c);
function* gen(res){
for(var i=0; i < funcs.length; i++){
yield funcs[i](res);
}
}
function run() {
var _results = [];
for(f of gen(_results)){
results.innerHTML += ('Yielded: ' + f + '<br/>');
_results.push(f);
}
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment