4 ms·
.map(fn) calls its callback with three arguments, the value, the index, and the full array. Then parseInt takes two arguments, the string and the base (radix).
by jacobwg 8y ago
.map(fn) calls its callback with three arguments, the value, the index, and the full array. Then parseInt takes two arguments, the string and the base (radix).
"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.
- contravariant 8y agoI see. I'll remember this example for when someone asks why you need types.
- shados 8y agothis is more than just types though. Typescript, even in strict mode, will still allow this! You need strict function arity/signature checking of some kind, which a dynamically typed language could have, and a statically typed language could lack.
- contravariant 8y agoIf a language can't detect the difference between a function a => f(a) and a function (a,b) => f(a,b) then I would consider it very weakly typed indeed. Dynamic vs static isn't really the issue, Python will also complain if you call a function with the wrong number of arguments. Then again I suppose that you could recreate JavaScripts behaviour even in the fairly strongly typed C# if you wanted to, by defining two overloaded versions of Map as follows: IEnumerable<B> Map<A,B>(this IEnumerable<B> list, Func<A,B> f) IEnumerable<B> Map<A,B>(this IEnumerable<B> list, Func<A,int,B> f) in that case C# would also choose the latter Map when you call it on a function with an optional int argument, similar to what JavaScript would do. However C# will never ignore an optional argument when you're passing around functions, so it's more consistent in that sense. And overloading a function in this way is not the best idea in the first place, it's just that JavaScript kind of encourages it.