Skip to content

Instantly share code, notes, and snippets.

@gunar
Last active April 29, 2018 17:13
Show Gist options
  • Save gunar/0d148814e740c1dd6b8f to your computer and use it in GitHub Desktop.
Save gunar/0d148814e740c1dd6b8f to your computer and use it in GitHub Desktop.
Function to sum an object values using recursion
// This is super slow though: http://jsperf.com/summing-objects/2
var sumObj = function (object) {
if (Object.keys(object).length) {
var firstKey = Object.keys(object)[0];
var clone = Object.assign({}, object);
delete clone[firstKey];
return parseInt(object[firstKey]) + sumObj(clone);
}
return 0;
};
@ericelliott
Copy link

Rule of thumb: If you write more code avoiding a loop than you'd write if you wrote the loop yourself, that's not functional style.

Using functional style should result in less code, not more. e.g.,

export default (numbers) => {
  const doubled = [];
  for(var i = 0; i < numbers.length; i++) {
    var newNumber = numbers[i] * 2
    doubled.push(newNumber)
  }
  return doubled;
};

vs declarative functional style:

export default (numbers) => numbers.map(n => n * 2);

@gunar
Copy link
Author

gunar commented Nov 13, 2015

Wow! Thank you very much, Eric!

I see now it could've been a simple reduce.

var sumObj = function (obj) {
  return Object.keys(obj).reduce(function (sum, next) {
    return sum + obj[next];
  }, 0);
};

@gunar
Copy link
Author

gunar commented Mar 5, 2016

Looks even neater with ES6:

const sumObj = obj => Object.keys(obj).reduce((sum, next) => sum + object[next], 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment