Created
February 17, 2022 21:40
-
-
Save gpDA/6eef734d9ecb16ef82d09e2c177ae78b 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 RecursiveHelperProductArr = (arr) => { | |
let index = arr.length - 1; | |
// helper function | |
const recur = (curIndex, acc) => { | |
acc *= arr[curIndex]; | |
if (curIndex === 0) return acc; | |
return recur(curIndex - 1, acc); // decrement the index and recursion | |
} | |
return recur(index, 1); | |
} | |
// recursion 2 - using built-in slice | |
const RecursiveSliceProductArr = (arr) => { | |
return (arr.length === 0) ? 1 : arr[0] * RecursiveSliceProductArr(arr.slice(1)); | |
} | |
const arr = [1,2,3,4,5]; // ==> 120 | |
console.log(RecursiveHelperProductArr(arr)); | |
console.log(RecursiveSliceProductArr(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment