Search code examples
javascriptgoogle-earth-engine

Can I map a function with more then one argument?


In EE (Google Earth Engine Javascript API) I can do

var listOfNumbers = [0, 1, 1, 2, 3, 5];
print('List of numbers:', listOfNumbers);

var add_ten = function(n) {
  var m = n + 10;
  return m;
}

var listOfNumbers_ = listOfNumbers.map(add_ten);
print('List of numbers:', listOfNumbers_);

What if I want to add x (or another value) instead of 10? Like

var listOfNumbers = [0, 1, 1, 2, 3, 5];
print('List of numbers:', listOfNumbers);

var add_x = function(n, x) {
  var m = n + x;
  return m;
}

var listOfNumbers_ = listOfNumbers.map(add_x);
print('List of numbers:', listOfNumbers_);

How do I pass that x?

I tried

var listOfNumbers_ = listOfNumbers.map(add_x(100));
print('List of numbers:', listOfNumbers_);

But got NaN is not a function.

Also tried

var listOfNumbers_ = listOfNumbers.map(add_x, 100);
print('List of numbers:', listOfNumbers_);

Then got the following interesting result (which I don't understand)

0,2,3,5,7,10

Solution

  • If you don't want to change your current function, then you can use partial application via Function#bind to supply one argument to it but not the other:

    var listOfNumbers = [0, 1, 1, 2, 3, 5];
    var add_x = function(n, x) {
      var m = n + x;
      return m;
    }
    
    var add_10 = add_x.bind(null, 10);
    
    var listOfNumbers_ = listOfNumbers.map(add_10);
    
    console.log(listOfNumbers_);

    Or even even:

    var listOfNumbers_ = listOfNumbers.map(add_x.bind(null, 10));
    

    Alternatively, you can use currying:

    var listOfNumbers = [0, 1, 1, 2, 3, 5];
    var add_x = function(n) {
      return function (x){
        var m = n + x;
        return m;
      }
    }
    
    var add_10 = add_x(10);
    
    var listOfNumbers_ = listOfNumbers.map(add_10);
    
    console.log(listOfNumbers_);

    Or even:

    var listOfNumbers_ = listOfNumbers.map(add_x(10));
    

    You can shorten the curried definition using arrow functions:

    var add_x = n => x => n+x;