Skip to content

Checkpoint: Lazy Batches

The Course
•
25 min study

This checkpoint combines the day's three ideas in one pipeline you have not seen solved: a hand-written iterator as the source, a generator stage that remembers state between values, and a limiting stage that must stop pulling and close everything below it.

changes(values) yields a string such as "5->6" each time a value differs from the one before it. The first value only sets the baseline, so it yields nothing. upTo(limit, values) yields at most limit values. It must not read another value once the limit is reached, and it rejects a limit that is not a non-negative integer with a RangeError.

Because both stages are generators, their checks and their reads happen when consumption starts, not when the pipeline is built. A limit of 0 is allowed and should read nothing at all, so think about what upTo does before its loop begins.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
function* values() {
  yield 1;
  yield 2;
  yield 3;
}

const iterator = values();

console.log(iterator.next().value);
console.log([...iterator].join(","));
Check your prediction
Text
1
2,3

Acceptance cases before you code

Write a small test plan before implementing batch boundaries and ownership. These cases extend the brief; they are not a second worked solution. Predict the expected behavior independently, then test through the public function. A good ordinary example and a good boundary example should catch different possible mistakes.

Case to tryWhat your result should demonstrate
upTo(2, ...) over readings that change three timesTwo changes, then the source logs closed; later readings are never read
Repeated equal readingsNo change is yielded for them, but each one is still read
upTo(0, ...)No changes and no reads, because no stage below upTo starts
upTo(-1, ...) built and not consumed, then spreadBuilding succeeds; the RangeError appears only when the spread starts

After the core task passes, deliberately break one rule and identify the case that notices it. Restore the implementation and explain the failure in terms of the contract, not the number of assertions. If a case requires a concept you have not recalled, revisit the relevant lesson before opening the solution.

Your turn

Exercise

Checkpoint: a lazy change detector

The hand-written sensor iterable is supplied; it logs every read and logs closed when its return() is called. Write changes(values) and upTo(limit, values) as described above, so that the four acceptance cases pass. Print:

Text
5->6 6->7
read 5, read 5, read 6, read 6, read 6, read 7, closed
limit 0: [] reads: 0
built with -1
RangeError: limit must be a non-negative integer
Your workspace JavaScript
function sensor(readings, log) {
  return {
    [Symbol.iterator]() {
      let index = 0;
      return {
        next() {
          if (index >= readings.length) return { value: undefined, done: true };
          log.push(`read ${readings[index]}`);
          return { value: readings[index++], done: false };
        },
        return() {
          log.push("closed");
          return { value: undefined, done: true };
        }
      };
    }
  };
}

function* changes(values) {
  // yield "previous->value" whenever a value differs from the one before it
}

function* upTo(limit, values) {
  // validate limit, then yield at most limit values without over-reading
}

const readings = [5, 5, 6, 6, 6, 7, 8, 9];

const log = [];
console.log([...upTo(2, changes(sensor(readings, log)))].join(" "));
console.log(log.join(", "));

const none = [];
console.log(`limit 0: [${[...upTo(0, changes(sensor(readings, none)))]}] reads: ${none.length}`);

const lazyCheck = upTo(-1, changes(sensor(readings, [])));
console.log("built with -1");
try {
  [...lazyCheck];
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}
Hint 1: the idea

changes needs memory that survives between yields: the previous value, and a way to tell "no previous value yet" apart from a real one. upTo is the stage that decides how much is read, so its limit check must come after a yield, never before a fresh read.

Hint 2: a first step

Start with upTo: validate, return early for 0, then a for...of that yields and counts. With changes still empty the first line is blank and the log shows every reading followed by no closed. Then write changes, and check that the log stops at read 7.

Show one solution
JavaScript
function sensor(readings, log) {
  return {
    [Symbol.iterator]() {
      let index = 0;
      return {
        next() {
          if (index >= readings.length) return { value: undefined, done: true };
          log.push(`read ${readings[index]}`);
          return { value: readings[index++], done: false };
        },
        return() {
          log.push("closed");
          return { value: undefined, done: true };
        }
      };
    }
  };
}

function* changes(values) {
  let started = false;
  let previous;
  for (const value of values) {
    if (started && value !== previous) {
      yield `${previous}->${value}`;
    }
    previous = value;
    started = true;
  }
}

function* upTo(limit, values) {
  if (!Number.isInteger(limit) || limit < 0) {
    throw new RangeError("limit must be a non-negative integer");
  }
  if (limit === 0) return;
  let sent = 0;
  for (const value of values) {
    yield value;
    sent += 1;
    if (sent === limit) return;
  }
}

const readings = [5, 5, 6, 6, 6, 7, 8, 9];

const log = [];
console.log([...upTo(2, changes(sensor(readings, log)))].join(" "));
console.log(log.join(", "));

const none = [];
console.log(`limit 0: [${[...upTo(0, changes(sensor(readings, none)))]}] reads: ${none.length}`);

const lazyCheck = upTo(-1, changes(sensor(readings, [])));
console.log("built with -1");
try {
  [...lazyCheck];
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}
Text
5->6 6->7
read 5, read 5, read 6, read 6, read 6, read 7, closed
limit 0: [] reads: 0
built with -1
RangeError: limit must be a non-negative integer

changes keeps previous in the generator's own local variables, which survive each suspension, and the started flag stops the first reading being compared with undefined. Repeated readings are still read, because only reading them shows they did not change. upTo counts after each yield, so once the second change has been delivered it returns without asking for another value. Returning ends its for...of, which closes changes, whose for...of closes the sensor: that is the closed entry, before 8 and 9 are read. With a limit of 0, upTo returns before its loop, so changes never starts and never even asks the sensor for an iterator. The RangeError for -1 appears at the spread, not at upTo(-1, ...), because a generator's body, including its validation, runs on the first next().

Change it and test it

Change upTo so it checks the count before yielding instead of after. Which acceptance case notices? Then replace the hand-written sensor with an array: which line of the log can no longer be observed, and why does the pipeline still behave the same?

Was this article helpful?

Your response is saved on this device.