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));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With