Simple JavaScript Generator
Illustrates how JavaScript generators work by using simple time-outs.
CSS
body{
font: 0.8em "Lucida Console", Monaco, monospace;
}
JavaScript
// Data sample, an array of "person" objects.
var people = [
{ name: 'Johnnie', age: 34 },
{ name: 'Priscilla', age: 23 },
{ name: 'Irene', age: 54 },
{ name: 'Marguerite', age: 43 },
{ name: 'Sonya', age: 32 },
{ name: 'Lionel', age: 45 },
{ name: 'James', age: 35 },
{ name: 'Melissa', age: 26 },
{ name: 'Loretta', age: 41 },
{ name: 'Kristen', age: 34 }
];
// "Generates" person objects that are under
// the age of 40. Note the function signature
// syntax and the yield statement.
function* youngerThan( age, source ) {
for ( var i in source ) {
if ( source[ i ].age < age ) {
yield source[ i ];
}
};
}
// Puts the the generator to use by listing
// all the "generated" people.
function listPeople( gen ) {
// Get's the next generator value. If the
// generator is done producing values, we
// exit.
var next = gen.next();
if ( next.done ) {
return;
}
// Display the person object in the DOM.
listPerson( next.value.name );
// Schedule the next iteration. We're only
// using a timeout here to illustrate the
// interleaving property of generators.
setTimeout( function() {
listPeople( gen );
}, 1000 );
}
// Puts a person element in the DOM.
function listPerson( name ) {
var p = document.createElement( 'p' );
p.appendChild( document.createTextNode( name ) );
document.body.appendChild( p );
}
// List all people under 40.
listPeople( youngerThan( 40, people ) );