ES6 Generator example.
A Pen by Origin1 Technologies on CodePen.
ES6 Generator example.
A Pen by Origin1 Technologies on CodePen.
<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" /> |