JavaScript/Generators

The term generator denotes a technique to generate a sequence of 'anything': numbers, strings, rows of database queries, elements of an array, nodes of a DOM tree, ...

It's used to avoid any memory overloading, by splitting the data in small chunks.

To use them, you must define a generator function first. Such functions are notated with an asterisk  directly behind the keyword , e.g.,.

When called, the function will not run instantly. It only runs just before the first occurrence of a  statement and returns a 'Generator object'. This 'Generator object' offers a  method. Calling  again and again returns the sequence elements one after the next. The elements arise by each  that is reached within the generator function.

Examples

 * The script generates a sequence of 4 integers.


 * Every  call returns not only a  ; there is also a boolean  . Hence you can call the generator in loops.


 * Generation out of an array, a database request, or a tree traversal.


 * Creation of the infinite sequence of all even numbers.

Parameters
The generator function may receive parameters. In this example, the 'pageSize' defines the number of array elements to be returned.