1

How would a js function like this be written?

map(add, [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])
 => [15, 18, 21, 24]

I'm trying to write a native js version of the clojure map function

(map + [1 2 3] [4 5 6])
=> [5 7 9]

where map accepts a function and any arbitrary number of arrays after that

9
  • 2
    With JavaScript code. Explain what you actually want, and what you've tried. Commented Nov 20, 2013 at 23:19
  • Are you asking how to write a varargs function in JavaScript? Commented Nov 20, 2013 at 23:21
  • 1
    Array#reduce may be best here. Something like [[1,2,3,4],[5,6,7,8],[9,10,11,12]].reduce(function(a,b) {return b.map(function(_,i) {return (a[i]||0)+b[i];});},[]); should do it. Commented Nov 20, 2013 at 23:24
  • That's not map, but zipWith sum what you are looking for Commented Nov 20, 2013 at 23:37
  • @Bergi... its definitely map in clojure =) Commented Nov 20, 2013 at 23:38

1 Answer 1

2

Something like

pythonic_map = function(fun) {
    var args = [].slice.call(arguments, 1)
    return args[0].map(function(_, i) {
        return fun.apply(null, args.map(function(x) { return x[i] }));
    });
}

Example:

function add(a, b, c) {
    return a + b + c
}

z = pythonic_map(add, [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])
console.log(z) // [15,18,21,24]

This uses the length of the first argument, to use the shortest/longest argument:

pythonic_map = function(fun) {
    var args = [].slice.call(arguments, 1);
    return args.reduce(function(m, x) {
        return (x.length < m.length) ? x : m; // or > for the longest
    }).map(function(_, i) {
        return fun.apply(null, args.map(function(x) { return x[i] }));
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm surprised the idea of mapping a multi-argument function over multiple arrays is so foreign to Javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.