Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply numbers in a closure

How to implement a locking function for multiplying an arbitrary number of numbers.

Example of a call:

multiply(1)(2)(3)(4)(5) // 120

To accomplish this task, it is necessary to redefine the toString method for the internal function, which should return the accumulated result, but I had result NaN.

function Multiply(arguments) {
  for (var i = 0; i < arguments.length; i++) {
    var number = arguments.length[i];
  }
  return function(res) {
    return number * res.valueOf();
  };
}
console.log(Multiply(5)(5)(6)(8));
like image 568
Igor Shvets Avatar asked Dec 24 '22 07:12

Igor Shvets


1 Answers

First of all do not use arguments as parameter in a function, because this variable is available in functions as array like object for the arguments of the function (arguments object).

Then you need to have an inner function m which uses the arguments and calculates the product and returns the function itself.

The inner function gets a toString method for getting the final result.

At last you need to call the inner function with all arguments of the outer function.

A small hint, take only a lower case letter for not instanciable function.

function multiply(...args) {
    function m(f, ...a) {
        p *= f;
        if (a.length) {
            m(...a);
        }
        return m;
    }

    var p = 1;            // neutral value for multiplication
    m.toString = _ => p;
    return m(...args);
}

console.log(multiply(5)(5)(6)(8));
console.log(multiply(2, 3, 4)(5)(6, 7));
like image 97
Nina Scholz Avatar answered Jan 10 '23 22:01

Nina Scholz