Find the bug · Easy
Fix the Number Parser (map + parseInt)
Easy Find the bug
parseAll(strings) converts an array of decimal integer strings (such as query-string values) into numbers.
The one-liner below looks idiomatic. It works for one value and fails for lists. Find the bug and fix it.
Example 1
Input: strings = ["7"] Output: [7]
Example 2
Input: strings = ["10", "10", "10"] Output: [10, 10, 10] Explanation: The buggy version returns [10, NaN, 2].
The buggy code
function parseAll(strings) {
return strings.map(parseInt);
}
function parseAll(strings: string[]): number[] {
return strings.map(parseInt);
}
Hints
Hint 1
What arguments does map pass to its callback?
Hint 2
What is the second parameter of parseInt?
Find and fix the bug
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the bug and the fix
Time O(n) · Space O(n)
The bug: map calls its callback with (element, index, array), and parseInt(string, radix) takes the index as the radix. parseInt("10", 1) is NaN (radix 1 is invalid) and parseInt("10", 2) is 2. Only index 0 works, because radix 0 means "guess".
The fix: pass only the element and an explicit radix: strings.map((s) => parseInt(s, 10)), or use Number (strings.map(Number)), which takes one argument.
Fixed version
function parseAll(strings) {
return strings.map((s) => parseInt(s, 10));
}
function parseAll(strings: string[]): number[] {
return strings.map((s) => parseInt(s, 10));
}
Common mistakes
map(Number)accepts""as 0 and"1e3"as 1000: say which behaviour you want.
More Code Clinic: Find the Bug problems
- Fix the Binary Search · Easy
- Fix the Two Sum Hash Map · Easy
- Fix the Longest Substring Without Repeats · Medium
- Fix Merge Intervals · Medium
- Fix the Mutable Default Argument · Easy
- Fix the Substring Check · Easy