-2

multiply(10)()()()(12) This a function call and we have to make a function to multiply 2 numbers

VLAZ
  • 26,331
  • 9
  • 49
  • 67

1 Answers1

0

You can curry the function and leverage rest parameters and spreading. If there are no arguments supplied then (...args) will be an empty array and .bind(this, ...args) will create a function without partially applying any values to it.

Once all arguments are satisfied, the function is immediately called.

const curry = f => function(...args) {
  if (f.length - args.length <= 0)
    return f.apply(this, args);
        
  return curry(f.bind(this, ...args));
}

const mul = (a, b) => a * b;
const multiply = curry(mul);

console.log(multiply(10, 12));       // = 120
console.log(multiply(10)(12));       // = 120
console.log(multiply(10)()(12));     // = 120
console.log(multiply(10)()()()(12)); // = 120

const obj = {
  x: 2,
  multiply: curry(function(a, b) {
    return a * b * this.x;
  })
}

console.log(obj.multiply(10)()()()(12)); // = 240
VLAZ
  • 26,331
  • 9
  • 49
  • 67