0

This function has to add all the constants in the array recursively using JavaScript. Any idea why I'm getting a type error in this recursion function?

const slowAdd = (array) => {
  if (array.length === 0) return 0;

  const restOfArray = array.slice(1);

  return array[0] + slowAdd(array[restOfArray]);
}

const dataArray = [2, 5, 7]
slowAdd(dataArray);

Same Problem with using helper function:

const fastSum = (array) => {
  return _fastSum(array, 0);
};

const _fastSum = (array, start) => {
  if (start === array.length) return 0;

  return array[start] + _fastSum(array, start + 1);
}

const dataArray = [2, 5, 7]
console.log(fastSum(dataArray));

Why does the fastSum recursion work, but the first doesn't.

3
  • array[restOfArray] is a single number, not a different array. EDIT: OK, actually restOfArray is the rest of the array. I misread it and thought it was just an index. At any rate array[restOfArray] certainly doesn't produce another array and slowAdd does expect an array Commented Dec 1, 2020 at 13:45
  • @VLAZ It will not even give a number. It will return undefined Commented Dec 1, 2020 at 13:49
  • @MaheerAli indeed. I initially misread the code and thought restOfArray would be an index. However, when it's an array, then most of the time it's going to produce undefined as you said. Commented Dec 1, 2020 at 13:51

2 Answers 2

2

restOfArray is itself an array and you are trying to use it as index of another array. array[restOfArray] will always return undefined.

you should pass restOfArray instead of array[restOfArray]

const slowAdd = (array)=>{
    
    if(array.length === 0) return 0;

    const restOfArray = array.slice(1);

    return array[0] + slowAdd(restOfArray);

}

const dataArray = [2, 5, 7]
console.log(slowAdd(dataArray));

//Same Problem with this one.

const fastSum = (array)=>{
    return _fastSum(array, 0);
};
const _fastSum = (array, start)=>{
    if(start === array.length) return 0;

    return array[start] + _fastSum(array, start + 1);

}

console.log(fastSum(dataArray));

Sign up to request clarification or add additional context in comments.

Comments

0

restOfArray is array

const slowAdd = (array) => {
  if (array.length === 0) return 0;

  const restOfArray = array.slice(1);

  return array[0] + slowAdd(restOfArray);
}

const dataArray = [2, 5, 7]
slowAdd(dataArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.