what-to-cook/src/logic.js
Peppa d4c20db42e WTC-16: пример в поле берётся из базы блюд
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 06:15:00 +05:00

89 lines
4.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { catalogItems } from "./catalog.js";
export function normalize(name) {
return String(name ?? "").replace(/\s+/g, " ").trim();
}
const fold = (s) => normalize(s).toLowerCase().replace(/ё/g, "е");
// Название из базы, если введённый текст ему точно равен (без учёта регистра).
export function canonical(name, catalog = []) {
const f = fold(name);
return catalog.find((c) => fold(c) === f) ?? normalize(name);
}
// Пример в поле: первое блюдо базы; пустая база — нейтральная подсказка без примера.
export function placeholderFor(catalog, t) {
const first = Array.isArray(catalog) ? catalog.find((d) => typeof d === "string" && d.trim()) : null;
return first ? t.placeholder.replace("{name}", first.toLowerCase()) : t.placeholderNeutral;
}
// Подсказки: блюда базы, у которых любое слово начинается с введённого; уже добавленные скрыты.
export function suggest(query, dishes, catalog, limit = 5) {
const q = fold(query);
if (!q) return [];
const have = new Set(dishes.map(fold));
return catalog
.filter((c) => !have.has(fold(c)) && fold(c).split(/[\s-]+/).some((w) => w.startsWith(q)))
.slice(0, limit);
}
export function addDish(dishes, name) {
const n = normalize(name);
if (!n) return dishes;
if (dishes.some((d) => d.toLowerCase() === n.toLowerCase())) return dishes;
return [...dishes, n];
}
// Нажатие «Добавить»: пустое название — ошибка "emptyName", список не меняется.
export function submitDish(dishes, name, catalog = []) {
if (!normalize(name)) return { dishes, error: "emptyName" };
const n = canonical(name, catalog);
if (dishes.some((d) => fold(d) === fold(n))) return { dishes, error: "alreadyAdded" };
return { dishes: addDish(dishes, n), error: null };
}
export function removeDish(dishes, name) {
return dishes.filter((d) => d !== name);
}
// Случайное блюдо, не равное last (если блюд больше одного). rnd — для тестов.
export function pickDish(dishes, last, rnd = Math.random) {
if (dishes.length === 0) return null;
const pool = dishes.length > 1 ? dishes.filter((d) => d !== last) : dishes;
const list = pool.length ? pool : dishes;
return list[Math.min(Math.floor(rnd() * list.length), list.length - 1)];
}
export function parseState(raw) {
try {
const s = JSON.parse(raw);
const dishes = Array.isArray(s?.dishes)
? s.dishes.filter((d) => typeof d === "string" && d.trim())
: [];
const last = typeof s?.last === "string" && dishes.includes(s.last) ? s.last : null;
return { dishes, last };
} catch {
return { dishes: [], last: null };
}
}
// Сложность блюда из общей базы (1–3) по названию без учёта регистра; у своих блюд — null.
export function difficultyOf(name, base = catalogItems) {
const n = normalize(name).toLowerCase();
return base.find((c) => c.name.toLowerCase() === n)?.level ?? null;
}
// «Полегче» (dir = -1) / «Посложнее» (dir = 1): блюдо списка со строго меньшей/большей сложностью.
// Блюда без сложности не участвуют; у текущего без сложности отсчёт от среднего.
// Нет подходящих — error "noEasier" / "noHarder", текущее блюдо остаётся.
export function pickByDifficulty(dishes, last, dir, rnd = Math.random, base = catalogItems) {
const cur = difficultyOf(last, base) ?? 2;
const pool = dishes.filter((d) => {
const l = difficultyOf(d, base);
return l !== null && d !== last && (dir < 0 ? l < cur : l > cur);
});
if (!pool.length) return { dish: last, error: dir < 0 ? "noEasier" : "noHarder" };
return { dish: pool[Math.min(Math.floor(rnd() * pool.length), pool.length - 1)], error: null };
}