the complexity comes from relying on a complex accumulator object instead just returning the average number ;)
This file contains 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