-
-
Save cbrunnkvist/7f11a5158b2e11580e02afc366281f33 to your computer and use it in GitHub Desktop.
the complexity comes from relying on a complex accumulator object instead just returning the average number ;)
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
const basket = [ | |
{ name:"apple", type: "fruit", calories: 52 }, | |
{ name:"broccoli", type: "vegetable", calories: 45 }, | |
{ name:"banana", type: "fruit", calories: 89 } | |
]; | |
class CaloriesAccumulator { | |
constructor(fruitCount = 0, avgCalories = 0) { | |
console.debug(`count: ${fruitCount}\tavg: ${avgCalories}`) | |
this.fruitCount = fruitCount | |
this.avgCalories = avgCalories | |
} | |
} | |
const { avgCalories } = basket.reduce((acc, currentFood) => { | |
if (currentFood.type !== "fruit"){ | |
return acc; | |
} | |
const newFruitCount = acc.fruitCount + 1; | |
const previousTotalCalories = acc.avgCalories * acc.fruitCount; | |
const newAvgCalories = (previousTotalCalories + currentFood.calories) / newFruitCount; | |
return new CaloriesAccumulator(newFruitCount, newAvgCalories); | |
}, new CaloriesAccumulator()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment