Reputation: 1
I need the most efficient way to calculate the total quantity for each base item by going through a list of cart items and sum up the quantities for all cart items having the same base item.
My CartItem looks something like:
export interface CartItem {
id: string;
baseItem: BaseItem;
quantity: number;
addOns: string[]
}
export interface BaseItem {
name: string;
id: string;
}
There can be multiple CartItems for the same BaseItem basis the different AddOns / Variations.
My current solution is to use a Map, and it does work, however I think there could be a faster more optimised way of doing this.
const itemQuantites: Map<string, number> = new Map<string, number>();
cart.items.forEach(
cartItem => {
// Check for a match, else add it to the Map
if (itemQuantites.has(cartItem.baseItem.id)) {
const currentQuantity = itemQuantites.get(cartItem.baseItem.id) ?? 0;
itemQuantites.set(cartItem.baseItem.id, currentQuantity + cartItem.quantity);
}
else {
itemQuantites.set(cartItem.baseItem.id, cartItem.quantity);
}
}
);
Upvotes: 0
Views: 36