Generators is an actively used design pattern.

?Years Old
  • Generators ranks in the top 50% of entities I track
  • the Generators wikipedia page
  • I have 12 facts about Generators. what would you like to know? email me and let me know how I can help.

Languages with Generators include csharp, javascript, python, ruby

Example from csharp:

// Method that takes an iterable input (possibly an array)
// and returns all even numbers.
public static IEnumerable<int> GetEven(IEnumerable<int> numbers) {
    foreach (int i in numbers) {
        if ((i % 2) == 0) {
            yield return i;
        }
    }
}

Example from javascript:

function* fibonacci(limit) {
    let [prev, curr] = [0, 1];
    while (!limit || curr <= limit) {
        yield curr;
        [prev, curr] = [curr, prev + curr];
    }
}
// bounded by upper limit 10
for (let n of fibonacci(10)) {
    console.log(n);
}
// generator without an upper bound limit
for (let n of fibonacci()) {
    console.log(n);
    if (n > 10000) break;
}
// manually iterating
let fibGen = fibonacci();
console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 2
console.log(fibGen.next().value); // 3
console.log(fibGen.next().value); // 5
console.log(fibGen.next().value); // 8
// picks up from where you stopped
for (let n of fibGen) {
    console.log(n);
    if (n > 10000) break;
}

Example from python:

https://wiki.python.org/moin/Generators

Example from ruby:

# Generator from an Enumerator object
chars = Enumerator.new(['A', 'B', 'C', 'Z'])

4.times { puts chars.next }

# Generator from a block
count = Enumerator.new do |yielder|
  i = 0
  loop { yielder.yield i += 1 }
end

100.times { puts count.next }

Last updated September 6th, 2019