Skip to curriculum
Jump to the editor

10.6. Generators: random numbers, a range and a search through nested data

Medium
Topics
20–35 min

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.

Signature

JAVASCRIPT
function randomInts(min, max)        // endless random integers from min to max
function range(start, end, step = 1) // start, start + step, … up to (not including) end
function findAll(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).

Requirements

randomInts

  1. Each value is min + Math.floor(Math.random() * (max - min + 1)), so every integer from min to max can appear and nothing outside it.
  2. It calls Math.random exactly once per value, and only when a value is asked for: creating the generator calls it zero times.
  3. It never finishes: done is always false.
  4. It throws a RangeError at the call, not at the first next(), when min or max is not an integer or min > max. min === max is allowed.

range

  1. range(start, end) gives start, start + 1, … while below end; range(end) starts at 0.
  2. 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.
  3. A range that cannot move toward end is empty: range(0), range(3, 3), range(5, 0), range(0, 5, -1).
  4. A step of 0 or NaN throws a RangeError at the call. end may be Infinity.

findAll

  1. 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.
  2. Array holes are skipped. Values inside a match are still searched.
  3. 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.
  4. 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.
  5. Each yielded path is its own array and never changes afterwards.
  6. A predicate that is not a function throws a TypeError at the call.

Examples

JAVASCRIPT
const dice = randomInts(1, 6);
dice.next().value;          // 4 (any integer from 1 to 6)
[...range(5)];              // [0, 1, 2, 3, 4]
[...range(10, 0, -3)];      // [10, 7, 4, 1]
[...range(0, 1, 0.25)];     // [0, 0.25, 0.5, 0.75]
range(0, 5, 0);             // RangeError, straight away
JAVASCRIPT
const data = { a: 1, b: [12, { c: 30 }], d: 4 };
[...findAll(data, (value) => typeof value === "number" && value > 10)];
// [{ path: ["b", 0], value: 12 }, { path: ["b", 1, "c"], value: 30 }]
JAVASCRIPT
const node = { name: "root", children: [] };
node.children.push(node);    // a cycle
[...findAll(node, (value, path) => path.at(-1) === "name")];
// [{ path: ["name"], value: "root" }]: the cycle is not followed

Environment

  • Plain JavaScript in a browser page; the tests call the globals randomInts, range and findAll from generators.js.
  • Use generator functions (function*). Helper functions are fine.
  • The tests replace Math.random with a fixed sequence for some checks, so call Math.random() itself (no other source of randomness).
  • Map, Set and class instances are walked like any object (by Object.keys); their entries are not part of this problem.

Hints

  1. A generator function's body does not run until the first next(). How can a check still happen at the call?
  2. Adding 0.1 ten times does not give exactly 1. What can you compute from the index instead?
  3. How does yield* help a recursive walk hand its results back up?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…