Created
February 17, 2022 21:20
-
-
Save gpDA/c234da5718077b5c371cc2df141a55eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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