Skip to content

Instantly share code, notes, and snippets.

@micimize
Created April 24, 2017 05:26
Show Gist options
  • Save micimize/2816dfdb8e383d28cefb8f6f053c2ae1 to your computer and use it in GitHub Desktop.
Save micimize/2816dfdb8e383d28cefb8f6f053c2ae1 to your computer and use it in GitHub Desktop.
recursion examples
// takes in any structure
// returns the sum of all numbers in all leaf nodes recursively
function deepSum (json) {
if (Array.isArray(json)) {
return json.reduce((sum, item) => sum + deepSum(item), 0)
} else if (typeof(json) === 'object') {
return Object.keys(json)
.reduce((sum, key) => sum + deepSum(json[key]), 0)
} else {
try {
return Number(json) || 0
} catch (e) {
return 0
}
}
}
// tail recursive version
// refactored for Object.values
function deepSum (json, sum = 0) {
if (typeof(json) === 'object') {
let items = (Array.isArray(json) ? json : Object.values(json))
return items.reduce((_sum, item) => deepSum(item, _sum), sum)
} else {
try {
return sum + (Number(json) || 0)
} catch (e) {
return sum
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment