Find the bug · #60 · Sort and search Hard JavaScript
The lunch menu shows breakfast items
A recursive menu flattener works the first time and mixes menus together after that.
On this page
The report
The search index flattens each restaurant menu into a list of dish names. The first menu indexes fine; every menu after it also contains all the dishes from the menus before it.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Flattens a nested menu into a list of dish names, for the search index.
const names = [];
function flattenMenu(items) {
for (const item of items) {
names.push(item.name);
if (item.children) flattenMenu(item.children);
}
return names;
}Read it, then pick a line.
Where does names live, and when is it ever emptied?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const breakfast = [{ name: 'Tea' }, { name: 'Toast', children: [{ name: 'Butter' }] }];
const lunch = [{ name: 'Thali' }];
console.log(flattenMenu(breakfast).join(', '));
console.log(flattenMenu(lunch).join(', '));It prints
Tea, Toast, Butter Tea, Toast, Butter, Thali
It should print
Tea, Toast, Butter Thali
Show the answer: the bug, the fix, and how you’d find it
The bug (lines 2, 3)
Line 2 keeps the result list outside the function, so it’s created once and shared by every call. The recursion needs one list per flatten, but the second menu’s dishes get added to the first menu’s list, and so on. Pass the list down the recursion instead (a default parameter makes a new one for each top-level call).
The fix
1// Flattens a nested menu into a list of dish names, for the search index.2const names = [];3function flattenMenu(items) {2function flattenMenu(items, names = []) {4 for (const item of items) {5 names.push(item.name);6 if (item.children) flattenMenu(item.children);5 if (item.children) flattenMenu(item.children, names);7 }8 return names;9}How you’d find it
- Reproduce with two menus flattened one after the other: the second result starts with the first menu’s dishes.
- Right the first time, wrong the second: something outlives the call.
namesis declared at the top level. - The recursion needs a shared list within one flatten, which is why it was moved out. Pass it as a parameter instead.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert.deepEqual(flattenMenu([{ name: 'a', children: [{ name: 'b' }] }]), ['a', 'b']);
assert.deepEqual(flattenMenu([{ name: 'x' }]), ['x']);Where else this bites
- Memo tables kept at module level in DSA solutions that are then run on several test cases.
- Python’s mutable default argument (see “New carts already have items”).