Skip to content

Instantly share code, notes, and snippets.

@trezy
Created June 21, 2022 18:45
Show Gist options
  • Save trezy/d726d1ca3ab68c9b4bcc8baa883cf64d to your computer and use it in GitHub Desktop.
Save trezy/d726d1ca3ab68c9b4bcc8baa883cf64d to your computer and use it in GitHub Desktop.
/**
* 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