Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. // takes in any structure
  2. // returns the sum of all numbers in all leaf nodes recursively
  3. function deepSum (json) {
  4. if (Array.isArray(json)) {
  5. return json.reduce((sum, item) => sum + deepSum(item), 0)
  6. } else if (typeof(json) === 'object') {
  7. return Object.keys(json)
  8. .reduce((sum, key) => sum + deepSum(json[key]), 0)
  9. } else {
  10. try {
  11. return Number(json) || 0
  12. } catch (e) {
  13. return 0
  14. }
  15. }
  16. }
  17.  
  18. // tail recursive version
  19. // refactored for Object.values
  20. function deepSum (json, sum = 0) {
  21. if (typeof(json) === 'object') {
  22. let items = (Array.isArray(json) ? json : Object.values(json))
  23. return items.reduce((_sum, item) => deepSum(item, _sum), sum)
  24. } else {
  25. try {
  26. return sum + (Number(json) || 0)
  27. } catch (e) {
  28. return sum
  29. }
  30. }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement