Files
counter/server/planner.js
T
2026-11-14 17:16:57 +00:00

88 lines
2.5 KiB
JavaScript

'use strict';
const SPLIT = { breakfast: 0.25, lunch: 0.35, dinner: 0.3, snack: 0.1 };
function round1(n) {
return Math.round(n * 10) / 10;
}
// Stable pseudo-random jitter so plans vary by day without changing on refresh.
function hash(str) {
let h = 2166136261;
for (let i = 0; i < str.length; i += 1) {
h ^= str.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return Math.abs(h);
}
function styleAllows(recipe, style) {
if (!style || style === 'any') return true;
if (style === 'high_protein') {
return recipe.tags.includes('high_protein') || recipe.protein_g >= 25;
}
if (style === 'vegetarian') {
return recipe.tags.includes('vegetarian') || recipe.tags.includes('vegan');
}
return recipe.tags.includes(style);
}
function totalsOf(items) {
const total = { kcal: 0, protein_g: 0, carbs_g: 0, fat_g: 0 };
for (const item of items) {
total.kcal += item.kcal;
total.protein_g += item.protein_g;
total.carbs_g += item.carbs_g;
total.fat_g += item.fat_g;
}
return {
kcal: Math.round(total.kcal),
protein_g: round1(total.protein_g),
carbs_g: round1(total.carbs_g),
fat_g: round1(total.fat_g),
};
}
/**
* Pick one recipe per meal slot that best fits the energy and protein budget.
* Falls back to any recipe in a slot when the style filters everything out.
*/
function generatePlan({ date = '', targetKcal = 2000, proteinTarget = 120, style = 'any', recipes }) {
const used = new Set();
const items = [];
for (const [meal, share] of Object.entries(SPLIT)) {
const kcalTarget = targetKcal * share;
const proteinForMeal = proteinTarget * share;
let pool = recipes.filter(
(recipe) => recipe.meal === meal && !used.has(recipe.id) && styleAllows(recipe, style)
);
if (!pool.length) {
pool = recipes.filter((recipe) => recipe.meal === meal && !used.has(recipe.id));
}
if (!pool.length) continue;
let best = null;
for (const recipe of pool) {
const jitter = (hash(`${date}:${recipe.id}`) % 21) / 10;
const score =
(Math.abs(recipe.kcal - kcalTarget) / Math.max(kcalTarget, 1)) * 100 +
Math.max(0, proteinForMeal - recipe.protein_g) * 1.5 +
jitter;
if (!best || score < best.score) best = { recipe, score };
}
used.add(best.recipe.id);
items.push(best.recipe);
}
return {
style,
items: items.map((recipe, index) => ({ ...recipe, sort: index })),
totals: totalsOf(items),
};
}
module.exports = { SPLIT, generatePlan, styleAllows, totalsOf };