node.jsrecursiondynamicparameters

NodeJS recursion with dynamic number of parameters


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:

  1. iteration: factor1: 1, factors: [1,1,1]
  2. iteration: 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?


Solution

  • 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)