munch-ease-frontend/src/components/shopping/shopping.js

43 lines
1.3 KiB
JavaScript
Raw Normal View History

export function groupsToItems(groups) {
2025-10-18 02:08:22 +00:00
return groups.map((group) => group.shoppingListItems).flat()
}
2025-07-30 08:10:22 +00:00
export function uniqueMeals(shoppingListItems) {
2025-10-18 02:08:22 +00:00
const mealsWithDuplicates = shoppingListItems.map((item) => item.meal).filter((m) => m)
2025-07-30 08:10:22 +00:00
2025-10-18 02:08:22 +00:00
const mealsLookup = mealsWithDuplicates.reduce((acc, meal) => {
acc[meal.id] ??= meal
return acc
}, {})
2025-07-30 08:10:22 +00:00
2025-10-18 02:08:22 +00:00
return Object.values(mealsLookup)
2025-07-30 08:10:22 +00:00
}
export function itemsToGroups(shoppingListItems) {
2025-10-18 02:08:22 +00:00
const ingredients_by_product_id = {}
const ingredients_by_name = {}
for (const item of shoppingListItems) {
if (item.ingredient.product) {
let group = ingredients_by_product_id[item.ingredient.product.id]
if (!group) {
group = ingredients_by_product_id[item.ingredient.product.id] = {
product: item.ingredient.product,
shoppingListItems: [],
}
2025-10-18 02:08:22 +00:00
}
group.shoppingListItems.push(item)
} else {
let group = ingredients_by_name[item.ingredient.name]
if (!group) {
group = ingredients_by_name[item.ingredient.name] = {
name: item.ingredient.name,
shoppingListItems: [],
2024-05-19 10:21:49 +00:00
}
2025-10-18 02:08:22 +00:00
}
group.shoppingListItems.push(item)
2024-05-19 10:21:49 +00:00
}
2025-10-18 02:08:22 +00:00
}
2024-05-19 10:21:49 +00:00
2025-10-18 02:08:22 +00:00
return [...Object.values(ingredients_by_product_id), ...Object.values(ingredients_by_name)]
}