Skip to content

Checkpoint: Failure Policy

The Course
•
25 min study

Today's three lessons each gave one rule. Errors: the first observed failure wins, whatever value it is, so presence needs its own flag. Ownership: copy and validate the options you depend on when you are created, and hand out snapshots that callers cannot change. Reentrancy: finish updating your own state before calling user code, because that code may call you back.

This checkpoint needs all three in one object. createFailureLog({ label, maxFailures }) records failures from a batch. It keeps the index and reason of the first one, counts all of them, and when the count reaches maxFailures it tells its onStop listeners, once, with a frozen summary. One of the test's listeners records another failure from inside the notification, so the log is re-entered while it is dispatching.

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 createCounter() {
  let n = 0;
  return {
    bump() {
      n += 1;
      return n;
    }
  };
}

const a = createCounter();
const b = createCounter();

a.bump();
a.bump();
b.bump();
console.log(a.bump(), b.bump());
Check your prediction
Text
3 2

Each call to createCounter makes a new n, and each returned object can only reach its own. The failure log below relies on the same thing: two logs never share a count or a first failure.

Acceptance cases before you code

Write a small test plan before implementing first failure preservation. 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
The caller changes options after creating the logThe summary still shows the original label, and the stop still happens at 2
The first failure's reason is undefinedIt stays the first failure; a later "timeout" does not replace it
A listener calls record while being notifiedNo second stop notice; the count still includes that failure
A listener receives the summaryIt is frozen, and it shows the state at the moment of stopping (count 2)
maxFailures: 0RangeError when the log is created

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 failure log with a stop notice

Fix createFailureLog so every acceptance case passes. The test code below the function is complete; do not change it. Print:

Text
listener saw: nightly | count 2 | first #2 undefined
frozen: true
stop notices: 2
now: nightly | count 4 | first #2 undefined
RangeError: maxFailures must be a positive integer
Your workspace JavaScript
function createFailureLog(options) {
  // First draft: reads options live, keeps the first *truthy* reason,
  // never notifies, and returns a plain object. Fix all four.
  let count = 0;
  let firstIndex;
  let firstReason;
  const listeners = [];

  return {
    record(index, reason) {
      count += 1;
      if (!firstReason) {
        firstIndex = index;
        firstReason = reason;
      }
    },
    onStop(listener) {
      listeners.push(listener);
    },
    summary() {
      return { label: options.label, count, firstIndex, firstReason };
    }
  };
}

const show = s => `${s.label} | count ${s.count} | first #${s.firstIndex} ${s.firstReason}`;

const options = { label: "nightly", maxFailures: 2 };
const log = createFailureLog(options);
options.label = "changed";
options.maxFailures = 99;

let notices = 0;
log.onStop(() => {
  notices += 1;
  log.record(7, new Error("during stop")); // re-enters the log
});
log.onStop(snapshot => {
  notices += 1;
  console.log(`listener saw: ${show(snapshot)}`);
  console.log(`frozen: ${Object.isFrozen(snapshot)}`);
});

log.record(2, undefined);
log.record(5, "timeout");
log.record(8, "late");

console.log(`stop notices: ${notices}`);
console.log(`now: ${show(log.summary())}`);

try {
  createFailureLog({ label: "x", maxFailures: 0 });
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}
Hint 1: the idea

Sort the four problems by lesson. Two are about what the log captures when it is created and what it hands out (ownership). One is about telling "no failure yet" apart from "the failure was undefined" (errors). One is about the order of "update my state" and "call user code" (reentrancy).

Hint 2: a first step

Start at the top: destructure label and maxFailures from options and validate maxFailures, then replace !firstReason with a hasFirst flag. Run it: the last line becomes the RangeError and now: shows nightly and #2 undefined. The notification comes last.

Show one solution
JavaScript
function createFailureLog(options) {
  const { label, maxFailures } = options;
  if (!Number.isInteger(maxFailures) || maxFailures < 1) {
    throw new RangeError("maxFailures must be a positive integer");
  }

  let count = 0;
  let hasFirst = false;
  let firstIndex;
  let firstReason;
  let stopped = false;
  const listeners = [];

  function summary() {
    return Object.freeze({ label, count, firstIndex, firstReason });
  }

  return {
    record(index, reason) {
      count += 1;
      if (!hasFirst) {
        hasFirst = true;
        firstIndex = index;
        firstReason = reason;
      }
      if (count >= maxFailures && !stopped) {
        stopped = true;
        const snapshot = summary();
        for (const listener of [...listeners]) listener(snapshot);
      }
    },
    onStop(listener) {
      listeners.push(listener);
    },
    summary
  };
}

const show = s => `${s.label} | count ${s.count} | first #${s.firstIndex} ${s.firstReason}`;

const options = { label: "nightly", maxFailures: 2 };
const log = createFailureLog(options);
options.label = "changed";
options.maxFailures = 99;

let notices = 0;
log.onStop(() => {
  notices += 1;
  log.record(7, new Error("during stop")); // re-enters the log
});
log.onStop(snapshot => {
  notices += 1;
  console.log(`listener saw: ${show(snapshot)}`);
  console.log(`frozen: ${Object.isFrozen(snapshot)}`);
});

log.record(2, undefined);
log.record(5, "timeout");
log.record(8, "late");

console.log(`stop notices: ${notices}`);
console.log(`now: ${show(log.summary())}`);

try {
  createFailureLog({ label: "x", maxFailures: 0 });
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}
Text
listener saw: nightly | count 2 | first #2 undefined
frozen: true
stop notices: 2
now: nightly | count 4 | first #2 undefined
RangeError: maxFailures must be a positive integer

Destructuring options at creation is the snapshot: changing options.label and options.maxFailures afterwards cannot move the stop point or rename the log. hasFirst keeps #2 undefined as the first failure even though undefined is falsy. The stop check sets stopped = true and takes the frozen summary before calling any listener. So when the first listener calls record(7, ...), the count goes to 3 but stopped is already true and no nested notice starts, while the second listener still receives the count-2 snapshot from the moment the log stopped. With stopped set after the loop, that reentrant record would start a nested notice, whose first listener records again, and so on until the stack overflows with a RangeError.

Change it and test it

Mutation-check your solution: move stopped = true to after the listener loop, then change { label, maxFailures } = options to reading options.label inside summary. Which acceptance case fails each time, and what does the output show? Restore each change before the next.

Was this article helpful?

Your response is saved on this device.