what-to-cook/src/logic.js

112 lines
5.2 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 inCatalog(name, catalog = []) {
const f = fold(name);
return catalog.some((c) => fold(c) === f);
}
// Пример в поле: первое блюдо базы; пустая база — нейтральная подсказка без примера.
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 hasRecipe(dishes, findRecipe) {
return dishes.some((d) => Boolean(findRecipe(d)));
}
// В списке есть блюдо без рецепта — тогда под списком нужна подпись, почему стоит «Рецепта нет».
export function hasNoRecipe(dishes, findRecipe) {
return dishes.some((d) => !findRecipe(d));
}
// Пример для подсказки «как получить рецепт»: первое блюдо базы с рецептом, которого ещё нет в списке.
export function recipeExample(dishes, catalog, findRecipe) {
if (!Array.isArray(catalog)) return null;
const have = new Set(dishes.map(fold));
return catalog.find((c) => typeof c === "string" && c.trim() && !have.has(fold(c)) && findRecipe(c)) ?? null;
}
// Подсказки: блюда базы, у которых любое слово начинается с введённого; уже добавленные скрыты.
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 };
}