How to use currying function to work if one of the argument contains multiple value?

Viewed 83

I have a higher order function , though the first case multiply(4,5) works as expected but is it possible to pass multiple argument like multiply(2)(4, 5). In this case the answer is 8, but can a curried function be created in such a way so that it gives 40 as result

function multiply(s) {
  return function(b) {
    return s * b;
  }

}

console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))

4 Answers

You could use rest parameters ... and collect all arguments on both functions and return the reduced result.

function multiply(...a) {
    return function(...b) {
        return [...a, ...b].reduce((a, b) => a * b);
    };
}

console.log(multiply(4)(5));       //  20
console.log(multiply(2)(4, 5));    //  40
console.log(multiply(3, 2)(4, 5)); // 120

function multiply(s) {
  return function(b) {
    for(key in arguments)s*=arguments[key];
    return s;
  }

}

console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))

I think its best to use arguments property in your case.

You could do something like this using arguments:

function multiply(s) {
  return function () {
    return Array.from(arguments).reduce(function(accumulator, currentValue) {
      return accumulator * currentValue;
    }, s);
  }
}

You could do it this way if you have one or more b arguments :

function multiply(s) {
  // Will contain the multiplication of all b arguments
  var result = 1;

  // ...b will return an the array arguments passed
  return function(...b) {

    // Loop through each of this array and update result
    for (var i = 0; i < b.length; i++) {
      result *= b[i];
    }

    // return the final result
    return s * result;
  }

}

console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))

Related