3 ms·
> Not many languages manage to implement map in a way that ["1", "2", "3"].map(parseInt) would result in [1, NaN, NaN] It may seem counterintuitive at first,
by actsasbuffoon 13y ago
> Not many languages manage to implement map in a way that ["1", "2", "3"].map(parseInt) would result in [1, NaN, NaN]
It may seem counterintuitive at first, but it makes sense when you consider the function signatures. The map function passes two arguments; the element, and its index. The index ends up being used as the radix, which causes this sequence of calls:
parseInt("1", 0);
parseInt("2", 1);
parseInt("3", 2);
I'd recommend creating a higher-order function that takes a function and returns a unary version:
function unary(fn) {
return function(arg) {
return fn(arg);
};
}
Then you could use it like this:
["1", "2", "3"].map(unary(parseInt));
// => [1, 2, 3]
I think the problem is that you assumed (not unreasonably) that [...].map(parseInt) was an eta reduction of [...].map(function(e) {return parseInt(e);}). Unfortunately it's not, which caused some unexpected results. This would happen in any language where the map function passes two arguments and the string-to-integer function has an optional second argument.
Consider the following Ruby (this is a really weird way to do it in Ruby, but I'm trying to make the method signatures match):
# This lambda has the same type signature as JavaScript's parseInt
parse_int = ->(str, radix = 10) { str.to_i radix }
# This converts the lambda to a block and calls it with each element
# from the array, along with its index.
%w[1 2 3].map.with_index &parse_int
# => ArgumentError: invalid radix 1
As an aside, I'm a recovering JavaScript hater as well. I've mostly made peace with JS, though there are still parts of the language that make my skin crawl (See this gist for my favorite example: https://gist.github.com/actsasbuffoon/7323667 https://gist.github.com/actsasbuffoon/7323667). That said, there are some parts of JavaScript that are genuinely great. I recommend reading JavaScript Allongé by Reginald Braithwaite. I'm scarcely exaggerating when I say the book completely changed the way I look at JavaScript.
- the_mitsuhiko 13y agoI don't know a single language where the standard map function passes two arguments instead of one. Python has the starmap function as an alternative in case someone really needs that.
- recursive 13y ago.net's .Select() method has both variants.
- actsasbuffoon 13y agoI agree that it's probably a bit unusual, and likely owes to the fact that all JS functions are variadic and ignore arity mismatches. Ruby's procs behave the same way, though its methods and lambdas are more traditional.