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

56 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-05-12 03:32:18 +00:00
export function mealToShoppingListSources(meal) {
const sources = [];
for (const recipe of meal.recipes) {
for (const ingredient of recipe.ingredients) {
sources.push({ ingredient, meal, recipe, });
}
}
for (const ingredient of meal.extra_ingredients) {
sources.push({ ingredient, meal, });
}
return sources;
}
2024-05-18 07:05:28 +00:00
export function requestsToSources(requests) {
const sources = [];
for (const request of requests) {
if (request.ingredient) {
sources.push(request);
}
else if (request.meal) {
sources.push(...mealToShoppingListSources(request.meal));
}
}
return sources;
}
2024-05-12 03:32:18 +00:00
export function removeMealFromShoppingListSources(sources, meal) {
2024-05-12 06:32:28 +00:00
return sources.filter(source => source.meal?.id !== meal.id);
2024-05-12 03:32:18 +00:00
}
export function groupByProduct(sources) {
2024-05-12 06:32:28 +00:00
const noProductKey = "no-product";
const noProduct = { name: "No product", };
2024-05-12 03:32:18 +00:00
const grouped = {};
for (const source of sources) {
2024-05-12 06:32:28 +00:00
const key = source.ingredient?.product?.id ?? noProductKey;
if (!key) {
continue;
}
if (!grouped[key]) {
grouped[key] = {
product: source.ingredient.product ?? noProduct,
2024-05-12 03:32:18 +00:00
sources: [],
};
}
2024-05-12 06:32:28 +00:00
grouped[key].sources.push(source);
2024-05-12 03:32:18 +00:00
}
return Object.values(grouped);
}