Fix the bug: map(parseInt) quietly returns the wrong numbers
The compare form on your shop posts back the ids of whatever boxes the customer
checked. Checkboxes hand you strings, so you convert them to numbers before you
look each product up. values.map(parseInt) reads like plain English, and it
runs without a single error.
Then read what it printed. The customer checked products 4, 8, 11 and 2. You
got back 4, NaN, 3, 2. Half of them are right, which is exactly what makes
this one dangerous: nothing crashed, nothing warned you, and product 11 quietly
became product 3. That is a real product page, for a real product, that nobody
asked for.
map is not broken and neither is parseInt. The bug lives in the handoff
between them: in what map actually passes to the function you handed it, and
in what parseInt does with an argument it never asked for. Notice that the
first id came back fine and the second is not a number at all. One function gave
four different kinds of answer to four similar strings, so whatever changes from
item to item is your suspect.
Your task: fix toIds so every string in values becomes the number it
looks like: ["4", "8", "11", "2"] returns [4, 8, 11, 2].
You'll practice:
Checking a plausible-looking result value by value instead of glancing at it
Seeing what map really passes to its callback, and what happens when the
function you passed it accepts more than one argument
Show a hint
Show solution
Previous Next