I'm stuck with a problem, and I cannot solve it in TypeScript. I'm using Angular, this code is from a service. I have this 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){}}
Now I want to add new ingredients to the array, and emit an event with a copy of the new array: this works:
newIngredients = [
new Ingredient('mais', 100),
new Ingredient('uccellini', 5)
];
addIngredients(newIngredients: Ingredient[]) {
this.ingredients.push(...ingredients);
this.ingredientsChanged.emit(this.ingredients.slice());
}
But I want to check if a new ingredient object exists in the ingredients array, and if it exists, sum the old and the new amount value in a single object, and push the updated object, then return a copy of the array.
Expected output:
[
new Ingredient('farina', 500),
new Ingredient('burro', 80),
new Ingredient('uccellini', 10)
new Ingredient('mais', 100)
];
I try with Set, WeakSet, Map and other way, but I do not know Typescript so much. This is where I'm stuck:
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());
}
Thanks for help