A generator produces values one at a time, only when asked. That makes some things easy that are awkward with arrays: a sequence that never ends (random test data), a sequence you do not want to build in full (a range of a million numbers when you need the first three), and a search that should stop the moment you have what you need (the first matching node in a large tree of nested data).
Write three functions in generators.js. Each returns a generator object, and each produces its values lazily.
functionrandomInts(min, max) // endless random integers from min to maxfunctionrange(start, end, step=1) // start, start + step, … up to (not including) endfunctionfindAll(data, predicate) // { path, value } for every match in nested data
randomInts(min, max): min and max are integers, both included. The generator never finishes.
range(start, end, step): with one argument, range(end) counts from 0. A negative step counts down.
findAll(data, predicate): predicate(value, path) is called for every value it visits; path is the list of keys from data to that value (numbers for array indexes, strings for object keys).
Each value is min + Math.floor(Math.random() * (max - min + 1)), so every integer from min to max can appear and nothing outside it.
It calls Math.random exactly once per value, and only when a value is asked for: creating the generator calls it zero times.
It never finishes: done is always false.
It throws a RangeErrorat the call, not at the first next(), when min or max is not an integer or min > max. min === max is allowed.
range
range(start, end) gives start, start + 1, … while below end; range(end) starts at 0.
With a step, value number i is exactly start + i * step (not a running sum), and the sequence stops before reaching end: below end for a positive step, above it for a negative one.
A range that cannot move toward end is empty: range(0), range(3, 3), range(5, 0), range(0, 5, -1).
A step of 0 or NaN throws a RangeError at the call. end may be Infinity.
findAll
It visits data itself first (path []), then walks arrays by index and objects by Object.keys, depth first: a value comes before everything inside it, and siblings come in order. It yields { path, value } for each value where predicate(value, path) is truthy.
Array holes are skipped. Values inside a match are still searched.
It is lazy: after the consumer stops (for example, break out of for...of), no more values are visited, so predicate is not called again.
A cycle does not loop forever: an object that is already one of the current value's ancestors is skipped. The same object reached twice without a cycle is visited both times.
Each yielded path is its own array and never changes afterwards.
A predicate that is not a function throws a TypeError at the call.