Skip to content

Instantly share code, notes, and snippets.

@gpDA
Created February 17, 2022 21:20
Show Gist options
  • Save gpDA/c234da5718077b5c371cc2df141a55eb to your computer and use it in GitHub Desktop.
Save gpDA/c234da5718077b5c371cc2df141a55eb to your computer and use it in GitHub Desktop.
// recursion 1 - using helper function
const RecursiveHelperSumArr = (arr) => {
let index = arr.length - 1;
// helper function
const recur = (curIndex, sum) => {
sum += arr[curIndex];
if (curIndex === 0) return sum;
return recur(curIndex - 1, sum); // decrement the index and recursion
}
return recur(index, 0);
}
// recursion 2 - using built-in slice
const RecursiveSliceSumArr = (arr) => {
return (arr.length === 0) ? 0 : arr[0] + RecursiveSliceSumArr(arr.slice(1));
}
const arr = [1,2,3,4,5]; // ==> 15
console.log(RecursiveHelperSumArr(arr));
console.log(RecursiveSliceSumArr(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment