Last active
April 29, 2018 17:13
-
-
Save gunar/0d148814e740c1dd6b8f to your computer and use it in GitHub Desktop.
Function to sum an object values using recursion
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
// 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; | |
}; |
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);
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);
};
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
Two considerations:
for
doesn't mean you're not micromanaging the looping logic.reduce()
. Use the right data structure for the job at hand. =)