Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement