Empty and single-element collections
Correct for many, wrong for none or one.
What it looks like
items[0]reached without asking whether there is an item.- A reduce with no initial value.
- An average, a maximum or a join computed before checking there is anything to compute it over.
Why it survives review
Every example anybody writes down has three or four elements in it, because that is what makes the behaviour clear. The empty case is not interesting to write a test for, and the single-element case looks like it must be covered by the many-element one. Neither is.
How to see it
- For every collection in the diff, ask what the function returns when it is empty — and whether that is a value the caller can tell apart from a real answer.
- Check the single-element case separately from the empty one. They fail differently.
- A guard clause deleted from a diff is a change in behaviour even though it deletes no logic.
A minimal pair
Correct
if (values.length === 0) return 0;
return values.reduce((a, b) => a + b);
Defective
return values.reduce((a, b) => a + b);
[] throws TypeError: Reduce of empty array with no initial value instead of returning 0.
Practise it
1 diff in the corpus carry this class. They are not listed, because knowing which diff contains what would make finding it a comprehension question about this page.
Go to the exercises