all repos — momix @ 623410e806f3318fb20af938664583ced886ce0e

A CLI tool to manage recipes for Thermomix

commands/select.ts (view raw)

 1import type { DatabaseSync } from "node:sqlite";
 2import { Checkbox } from "@cliffy/prompt";
 3import { Table } from "@cliffy/table";
 4
 5export default async (db: DatabaseSync) => {
 6  const recipes = db.prepare("SELECT * FROM recipes").all();
 7
 8  const choices = await Checkbox.prompt({
 9    message: "Select recipes",
10    options: recipes.map((recipe) => ({
11      name: recipe.name as string,
12      value: recipe,
13    })),
14  });
15
16  const rawIngredients = choices.flatMap((recipe) =>
17    JSON.parse(recipe.ingredients as string)
18  );
19
20  const ingredients = rawIngredients.reduce((acc, ingredient) => {
21    const existingIngredient = acc.find(
22      (i) => i.name === ingredient.name && i.unit === ingredient.unit
23    );
24    if (existingIngredient) existingIngredient.value += ingredient.value;
25    else acc.push(ingredient);
26    return acc;
27  }, [] as { name: string; value: number; unit: string }[]);
28
29  const table = new Table(
30    ...ingredients.map((item) => [item.name, item.value, item.unit])
31  ).header(["Name", "Value", "Unit"]);
32
33  console.log(table.border().sort().toString());
34};