Created
January 7, 2021 02:36
-
-
Save StackTrac3/09fee0b7db4c80147dfa4f0f2c293664 to your computer and use it in GitHub Desktop.
Recursion: An important intermediate level concept for nested processing
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: a function may call itself and work with the return value. | |
// It can do this multiple times before returning the original execution | |
const getDeepTotal = function deepTotal(inputArray) { | |
let total = 0 | |
inputArray.forEach((el)=>{ | |
total += Array.isArray(el) ? deepTotal(el) : el | |
}) | |
return total | |
} | |
console.log(getDeepTotal([1, 2, [1, 2, 3], 2, 3])) | |
// >> 14 | |
// Recursion may cause endless | |
// loops, so do check inputs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment