Created
June 21, 2022 18:45
-
-
Save trezy/d726d1ca3ab68c9b4bcc8baa883cf64d to your computer and use it in GitHub Desktop.
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
/** | |
* Add all items in an array of numbers. | |
*/ | |
function addArray(array) { | |
return array.reduce((a, b) => a + b) | |
} | |
/** | |
* Calculate total stats (keyed by category), then generate | |
* additional meta stats based on initial calculations. | |
*/ | |
function calculateTotals(input) { | |
return Object.entries(input) | |
.reduce((accumulator, [key, values], index, array) => { | |
accumulator[key] = addArray(values) | |
if (index === (array.length - 1)) { | |
const allValues = Object.values(accumulator) | |
accumulator.all = addArray(allValues) | |
} | |
return accumulator | |
}, {}) | |
} | |
// Result: | |
calculateTotals({ | |
cats: [1, 2, 3, 4, 5], | |
dogs: [6, 7, 8, 9, 10], | |
}) | |
// { | |
// cats: 15, // 1 + 2 + 3 + 4 + 5 | |
// dogs: 40, // 6 + 7 + 8 + 9 + 10 | |
// total: 55, // 15 + 40 | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment