Skip to content

Instantly share code, notes, and snippets.

@cbrunnkvist
Forked from ekrem-aktas/avg_with_reduce.js
Last active July 26, 2022 13:52
Show Gist options
  • Save cbrunnkvist/7f11a5158b2e11580e02afc366281f33 to your computer and use it in GitHub Desktop.
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 ;)
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