by hkjkahfjddd · 8y ago · 0 comments
To save everyone from having to look this up on Stack Overflow:
.map passes two arguments to the function it calls - the value and the index. The parseInt function takes up to two arguments, a string and a radix.
So there’s nothing broken here about .map, you just aren’t expecting the second optional argument for parseInt.
So the actual equivalents are: ['1','1','1'].map(parseInt)
And
['1','1','1'].map((n, index) => parseInt(n, index))
In this case, the index of the element (1, 2, 3) is getting passed as the radix with which to parse the element (1, 1, 1).
[1, 2, 3, 4].reduce((x, y) => Math.min(x, y))
should be 1 but [1, 2, 3, 4].reduce(Math.min)
should be NaN, for similar reasons. Unfortunately it's a recurring theme in JS that a lot of useful functions have optional extra parameters and a lot of useful higher order functions pass extra context to their callbacks, causing many traps for the unwary if you try to use these tools in a style that works fine in most functional programming languages."1" of base 0 is 1
"1" of base 1 is NaN
"1" of base 2 is 1
The gotcha here is if you map(fn), you're going to get all three arguments sent to the fn, where map(v => fn(v)) explicitly only sends the first one.
['1', '2', '3'].map(parseInt)
This would be a bummer to be put on-the-spot to answer. It was fun while not being in an interview though.That's just about language specifics, not a question for seniors in my opinion.