Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't mapping over `parseInt` point-free style work as expected?

I'm running the following in the Node.JS console:

> ["30", "31", "32"].map(x => parseInt(x))
[ 30, 31, 32 ]
> ["30", "31", "32"].map(parseInt)
[ 30, NaN, NaN ]

Why aren't these expressions identical? Is there a semantic difference in calling a function in point-free style as opposed to an anynomous function?

like image 273
Nikolai Prokoschenko Avatar asked Mar 20 '26 00:03

Nikolai Prokoschenko


1 Answers

parseInt accepts two arguments: the numeric string and the base. Array#map provides the element and the index as the first two arguments to its callback, which makes some of the numbers unparseable (the main cause likely being that there are digits that are invalid for the specified base, such as having the digit 2 when parsing a string as binary), resulting in NaN. The Number function can be used instead to avoid this pitfall, as it ignores all arguments except the first.

["30", "31", "32"].map(Number)
like image 165
Unmitigated Avatar answered Mar 21 '26 14:03

Unmitigated