I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients:
private ingredients: Ingredient[] = [
new Ingredient('farina', 500),
new Ingredient('burro', 80),
new Ingredient('uccellini', 5)
];
This is the model:
export class Ingredient {constructor(public name: string, public amount: number){}}
I want to add new ingredients to the array and trigger an event with a copy of the updated array. This method works:
newIngredients = [
new Ingredient('mais', 100),
new Ingredient('uccellini', 5)
];
addIngredients(newIngredients: Ingredient[]) {
this.ingredients.push(...ingredients);
this.ingredientsChanged.emit(this.ingredients.slice());
}
However, I now aim to check if a new ingredient object already exists in the ingredients array. If it does, I need to combine the amounts and update the existing object before pushing it back into the array and returning a copy.
Desired output:
[
new Ingredient('farina', 500),
new Ingredient('burro', 80),
new Ingredient('uccellini', 10)
new Ingredient('mais', 100)
];
I've experimented with Set, WeakSet, Map, and other approaches, but my limited knowledge of TypeScript has me stuck at this point:
addIngredients(newIngredients: Ingredient[]) {
let hash = {};
this.ingredients.forEach(function (ingr) {
hash[ingr.name] = ingr;
});
let result = newIngredients.filter(function (ingr) {
if (!(ingr.name in hash)) {
return !(ingr.name in hash);
} else {
// ???
}
});
this.ingredients.push(...result);
this.ingredientsChanged.emit(this.ingredients.slice());
}
Any assistance would be greatly appreciated. Thank you!