Skip to content

Instantly share code, notes, and snippets.

@gpDA
Created February 17, 2022 21:40
Show Gist options
  • Save gpDA/6eef734d9ecb16ef82d09e2c177ae78b to your computer and use it in GitHub Desktop.
Save gpDA/6eef734d9ecb16ef82d09e2c177ae78b to your computer and use it in GitHub Desktop.
// 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