An invariant holds across a family of valid inputs. For a pure mapping operation, output length equals input length, each result corresponds to its original position, and input values remain unchanged. The pool adds a peak-active bound and a no-new-starts-after-failure rule.
You can exercise small deterministic input families without introducing a testing library. Test lengths zero through several values and more than one limit. Keep schedules controlled separately; a loop over lengths alone does not test out-of-order completion.
Mutation checking asks whether existing expectations distinguish correct code from a plausible broken version. If changing indexed assignment to push still passes every test, the order contract is untested. If removing cleanup still passes, your lifecycle claim lacks evidence.
Do not write dozens of assertions that simply repeat implementation steps. Test outcomes and relationships a caller depends on. A passing mutation experiment supports those particular claims; it does not prove every possible defect is detected.
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.
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
for (let length = 0; length <= 4; length++) {
const values = Array.from({ length }, (_, index) => index);
const doubled = values.map(value => value * 2);
assert(doubled.length === values.length, "length");
assert(
doubled.every((value, index) => value === index * 2),
"positions"
);
}
console.log("5 input families passed");Check your prediction
5 input families passedTest a family of inputs with a shared rule
An invariant describes behavior across multiple cases. For a pure reverse, output length is preserved, reversing twice restores the values, and the input stays unchanged. These properties catch different defects; no one property proves the entire algorithm correct.
Use small generated families you can inspect without a property-testing framework. Include empty and repeated-value cases, and still keep a few explicit expected outputs. A wrong implementation can satisfy one algebraic property by accident, such as returning its input unchanged.
function reverse(values) {
return [...values].reverse();
}
for (const values of [[], [1], [1, 2], [1, 1, 2]]) {
const twice = reverse(reverse(values));
if (JSON.stringify(twice) !== JSON.stringify(values)) {
throw new Error("Round trip failed");
}
}
console.log("4 round trips passed");Check your prediction
4 round trips passedThe round-trip property covers a family, but an identity function also passes it. Combine it with a concrete directional expectation and ownership checks.
const before = [1, 2, 3];
const after = [...before].reverse();
if (after.join(",") !== "3,2,1" || before.join(",") !== "1,2,3") {
throw new Error("Contract failed");
}
console.log("order and nonmutation passed");Check your prediction
order and nonmutation passedThe explicit output distinguishes reversal from doing nothing. The second check distinguishes a copying reverse from mutating the caller’s array.
Try the rule on new inputs
For a pool, propose invariants for result length, input order and active-call bounds. Explain which need controlled schedules as well as small input families. Mutate one rule and identify the distinguishing test.
Debug a plausible mistake
Repair rejection without state loss
Keep the original mapping after rejecting an existing ID. Print Rejected then 1. Replace the hard-coded identity check with a real uniqueness policy and test another existing ID too.
Predict the supplied program's actual behavior first. It runs without an error, but breaks the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.
function addUnique(values, id, value) {
values.set(id, value);
if (id === "A") {
throw new Error("Duplicate");
}
}
const values = new Map([["A", 1]]);
try {
addUnique(values, "A", 99);
} catch (error) {
console.log("Rejected");
}
console.log(values.get("A"));Hint 1: the idea
Throwing after a mutation can report failure while leaving corrupted state behind.
Hint 2: a first step
Check membership before changing the map and derive duplicate status from its keys.
Show one solution
function addUnique(values, id, value) {
if (values.has(id)) {
throw new Error("Duplicate");
}
values.set(id, value);
}
const values = new Map([["A", 1]]);
try {
addUnique(values, "A", 99);
} catch (error) {
console.log("Rejected");
}
console.log(values.get("A"));Rejected
1The original printed Rejected and then 99: it wrote the new value first and only then decided the ID was a duplicate, so the caller was told the operation failed while the map had changed anyway. Checking values.has(id) before set makes the rejection happen while the state is still untouched, and it works for any existing ID, not just "A". The invariant to test is "a rejected call leaves the map exactly as it was": compare the value after the catch, not only whether an error was thrown.
Run a mutant against the suite
A mutation check is easy to describe and easy to skip, so here is one in full. indexedMap is the correct helper; pushMap is the same code with one plausible edit, the kind a refactor could introduce. The same suite runs against both and prints each check's result. Before running, decide which checks you expect the mutant to fail.
async function main() {
async function indexedMap(values, mapper) {
const results = [];
await Promise.all(
values.map(async (value, index) => {
results[index] = await mapper(value);
})
);
return results;
}
// Mutant: one plausible edit, push instead of indexed assignment.
async function pushMap(values, mapper) {
const results = [];
await Promise.all(
values.map(async value => {
results.push(await mapper(value));
})
);
return results;
}
// Resolves later inputs first: the schedule an ordering bug needs.
function reverseFinisher() {
const gates = [];
const mapper = value =>
new Promise(resolve => gates.push(() => resolve(value * 10)));
const releaseAll = () => [...gates].reverse().forEach(open => open());
return { mapper, releaseAll };
}
async function suite(map) {
const results = [];
const check = (name, ok) => results.push(`${name} ${ok ? "pass" : "FAIL"}`);
let lengthsOk = true;
for (let length = 0; length <= 3; length++) {
const input = Array.from({ length }, (_, i) => i);
const output = await map(input, async n => n * 10);
lengthsOk &&= output.length === length;
}
check("lengths", lengthsOk);
const input = [1, 2, 3];
const inOrder = await map(input, async n => n * 10);
check("in-order", inOrder.join() === "10,20,30");
check("input kept", input.join() === "1,2,3");
const schedule = reverseFinisher();
const pending = map([1, 2, 3], schedule.mapper);
schedule.releaseAll();
check("reversed finish", (await pending).join() === "10,20,30");
return results.join(" | ");
}
console.log(`indexed: ${await suite(indexedMap)}`);
console.log(`push: ${await suite(pushMap)}`);
}
main();Check your prediction
indexed: lengths pass | in-order pass | input kept pass | reversed finish pass
push: lengths pass | in-order pass | input kept pass | reversed finish FAILThe suite runs four checks against each implementation. Three of them cannot tell indexedMap from the push mutant: every length is right, the input is unchanged, and when the mapper finishes in input order, pushing happens to give the same array. Only "reversed finish" holds the three calls and releases them last-first, so push records 30,20,10. That one failing line is the evidence that the suite actually tests the order contract. If every check had passed for the mutant too, the suite would be claiming more than it checks.
Trace the contract before building
An invariant describes state that must remain valid across every allowed transition, such as active work never exceeding its limit. Private fields or helper names do not enforce it automatically. Locate every statement that can change the relevant state.
A rejection test should inspect state after the exception: throwing after a write can still destroy the old value. Mutation checks should keep the program compilable and fail a named behavioral expectation. If the mutation only creates a syntax error, it provides no evidence that your invariant was actually tested.
Your turn
A suite that kills two mutants
chunk(values, size) splits an array into pieces of size, with a shorter last piece if needed. Two mutants are supplied: one silently drops a short final piece, the other empties the caller's array. Write suite(chunkFn) that checks invariants, not specific outputs: all items are kept in order, every piece except the last has exactly size items and the last has 1 to size, and the input is unchanged. Run it over lengths 0 to 7 and sizes 1 to 3 and report the first failure. Print:
correct: pass
drops tail: FAIL (items lost, length 1, size 2)
splices: FAIL (input changed, length 1, size 1)function chunk(values, size) {
const out = [];
for (let start = 0; start < values.length; start += size) {
out.push(values.slice(start, start + size));
}
return out;
}
// Two plausible mutants of chunk.
function chunkDropsTail(values, size) {
const out = [];
for (let start = 0; start + size <= values.length; start += size) {
out.push(values.slice(start, start + size));
}
return out;
}
function chunkSplices(values, size) {
const out = [];
while (values.length > 0) out.push(values.splice(0, size));
return out;
}
function suite(chunkFn) {
// For several lengths and sizes, check the invariants and return
// "pass" or "FAIL (reason, length L, size S)" for the first failure.
return "pass";
}
console.log(`correct: ${suite(chunk)}`);
console.log(`drops tail: ${suite(chunkDropsTail)}`);
console.log(`splices: ${suite(chunkSplices)}`);Hint 1: the idea
Three relationships hold for every valid input: flattening the pieces gives back the input, the piece sizes follow the rule, and the input still has its original length afterwards. Checking relationships rather than writing out expected arrays is what lets one suite cover 24 input families.
Hint 2: a first step
Write the two nested loops and build input as [0, 1, ..., length - 1] so that the flattened output must equal the indexes. Check only "items kept" first. Run it: the drops-tail mutant should already fail, while the splice mutant may still pass. Then add the input check.
Show one solution
function chunk(values, size) {
const out = [];
for (let start = 0; start < values.length; start += size) {
out.push(values.slice(start, start + size));
}
return out;
}
// Two plausible mutants of chunk.
function chunkDropsTail(values, size) {
const out = [];
for (let start = 0; start + size <= values.length; start += size) {
out.push(values.slice(start, start + size));
}
return out;
}
function chunkSplices(values, size) {
const out = [];
while (values.length > 0) out.push(values.splice(0, size));
return out;
}
function suite(chunkFn) {
for (let length = 0; length <= 7; length++) {
for (const size of [1, 2, 3]) {
const input = Array.from({ length }, (_, i) => i);
const output = chunkFn(input, size);
const flat = output.flat();
const sameItems = flat.length === length && flat.every((value, i) => value === i);
const sizesOk = output.every((part, i) =>
i < output.length - 1 ? part.length === size : part.length >= 1 && part.length <= size
);
const inputKept = input.length === length;
if (!sameItems) return `FAIL (items lost, length ${length}, size ${size})`;
if (!sizesOk) return `FAIL (bad sizes, length ${length}, size ${size})`;
if (!inputKept) return `FAIL (input changed, length ${length}, size ${size})`;
}
}
return "pass";
}
console.log(`correct: ${suite(chunk)}`);
console.log(`drops tail: ${suite(chunkDropsTail)}`);
console.log(`splices: ${suite(chunkSplices)}`);correct: pass
drops tail: FAIL (items lost, length 1, size 2)
splices: FAIL (input changed, length 1, size 1)Using 0..length-1 as the input makes "items kept in order" a one-line check: the flattened output must be exactly its indexes. The drops-tail mutant fails at the first family that needs a short final piece (length 1, size 2). The splice mutant returns correct pieces, so the items and sizes checks both pass for it; only inputKept notices, because splice empties the caller's array. Each check kills a different mutant, which is evidence that each one earns its place. A suite that only compared chunk([1, 2, 3, 4, 5], 2) with an expected array would have caught the first mutant and missed the second.
Change it and test it
Mutate reversed to call reverse directly on its input. Confirm your nonmutation expectation fails. Explain why length zero and one alone would miss this mutation. For the task pool, add a schedule case rather than assuming more input sizes test concurrency.
Completion is saved in this browser only. It does not measure mastery.