I'm never to NodeJS and therefore struggling with a recursive multiplication function. The problem seems to be that in the recursion the input parameters are an array which is then assigned to the first value instead of value by value. Here's the code
const multiply = (factor1, ...factors) => {
if (factors.length > 1){
return Math.round(factor1 * multiply(factors) * scale) / scale;
}
const factor2 = factors[0];
return Math.round(factor1 * factor2 * scale) / scale;
}
so calling with: multiply(1,1,1,1)
leads to:
factor1: 1, factors: [1,1,1]
factor1: [1,1,1], factors: Array(0)
how can I achieve to have in the second iteration factor1: 1, factors: [1,1]
, without checking if factor1 is an array?
The issue is when you recursively call multiply
, you don't pass each number as a separate parameter, you pass factors
which is an array, therefore multiply gets a single array parameter.
Two ways of fixing this, either using the spread syntax
multiply(...factors)
Or you can use apply to invoke multiply and pass the parameters as an array
multiply.apply(null, factors)