@thereforejs/food-finder 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,10 +46,24 @@ You get:
46
46
  - `exact`: the whole name. Spaces never matter: "Weizenmehl Typ 550" is "Weizen Mehl, Type 550".
47
47
  - `prefix`: the start of the name, ending at a word: "Weizenmehl" finds "Weizen Mehl, Type 405",
48
48
  never "Weizenmehlschwitze".
49
- - `words`: every word of the query is a whole word of the name, any order.
49
+ - `words`: every word of the query is a whole word of the name, any order. Singular and plural
50
+ are one word: "Zwiebel" finds "Zwiebeln gebraten", "Tomaten" finds "Tomate roh".
50
51
  - `compound`: a word of the query is the last part of a compound: "Butter" finds "Kakaobutter".
51
- - `partial`: only when no name holds the whole query, the names that hold the most of it.
52
+ - `start`: only when no name holds every word whole, the last word still being typed, from three
53
+ letters or two digits: "sulta" finds "Rosine/Sultanine", "butt" "Süßrahmbutter", "roggenmehl
54
+ 11" "Roggen Mehl, Type 1150". "ei" stays "Hühnerei".
55
+ - `partial`: only when no name holds the whole query, the names that hold the most of it. A part
56
+ that is only a preparation ("gedünstet") or a short word ("der") is no hit.
57
+ - `fuzzy`: only when nothing else is found, every word no name holds read as its nearest known
58
+ word, one letter off from five letters, two from seven: "Kartofel" finds "Kartoffel",
59
+ "Spagetti gekocht" the cooked pasta. Short words are never read so: "Eis" stays "Eis".
52
60
  - **`meant`**: found through a meaning (below), not the name.
61
+
62
+ A preparation ("gekocht", "gebraten", "Dose") picks the variant of what the other words mean:
63
+ "Spaghetti gekocht" is "Teigwaren eifrei, gekocht", "Ei gekocht" is "Hühnerei gekocht", not
64
+ "Entenei gekocht". Where the food has no such variant, the food itself comes with the preparation
65
+ missed, never another food that merely shares it.
66
+
53
67
  - **`missed`**: the words of the query, as read, that the name does not hold (`partial` only).
54
68
 
55
69
  Options of `search`: `limit` (at most this many hits) and `group` (only codes starting with it, the
@@ -107,23 +121,25 @@ const finder = createFinder(
107
121
 
108
122
  One entry point per language, so a German application holds no English:
109
123
 
110
- | Import | Reads |
111
- | ------------------------------------ | ---------------------------------------------------------------- |
112
- | `@thereforejs/food-finder/de` | German: ß/ä/ö/ü typed as ss/ae/oe/ue, "Typ" as "Type", compounds |
113
- | `@thereforejs/food-finder/en` | English: accents typed without them |
114
- | `.../de/meanings`, `.../en/meanings` | the meanings of each language, only when you import them |
124
+ | Import | Reads |
125
+ | ------------------------------------ | ------------------------------------------------------------------------------------------------ |
126
+ | `@thereforejs/food-finder/de` | German: ß/ä/ö/ü typed as ss/ae/oe/ue, other accents dropped, "Typ" as "Type", plurals, compounds |
127
+ | `@thereforejs/food-finder/en` | English: accents typed without them, plurals |
128
+ | `.../de/meanings`, `.../en/meanings` | the meanings of each language, only when you import them |
115
129
 
116
130
  ## Size
117
131
 
118
- Measured 2026-10-29, an application built with the Vite+ bundler, minified, gzip:
132
+ Measured 2026-11-01 with `vpx scripts/size.ts` after `vp pack`: an application per entry, built with
133
+ the Vite+ bundler, minified, gzip:
119
134
 
120
135
  | Application | App part | Names, loaded on first use |
121
136
  | ------------------------ | -------- | -------------------------- |
122
- | `/de` | 2,255 B | 69,641 B |
123
- | `/de` and `/de/meanings` | 2,390 B | 69,641 B |
124
- | `/en` | 2,173 B | 67,923 B |
137
+ | `/de` | 3,603 B | 70,882 B |
138
+ | `/de` and `/de/meanings` | 4,789 B | 70,882 B |
139
+ | `/en` | 3,326 B | 69,116 B |
125
140
 
126
- On the 7,108 German names, `createFinder` takes about 65 ms and a search about 10 to 40 ms.
141
+ On the 7,152 German names, `createFinder` takes about 75 to 95 ms (the first call up to 130 ms) and a
142
+ search about 9 to 40 ms; a mistyped one, read word by word, up to about 65 ms.
127
143
 
128
144
  ## License
129
145
 
@@ -1,13 +1,70 @@
1
1
  // src/de/meanings.ts
2
2
  const meanings = {
3
+ Balsamico: ["R125000"],
4
+ Bier: ["P163000"],
5
+ Bockshornklee: ["R_000035"],
6
+ "Brauner Zucker": ["S112000"],
7
+ Brot: [
8
+ "B251000",
9
+ "B271000",
10
+ "B311000"
11
+ ],
3
12
  Butter: ["Q630000"],
13
+ Chili: ["G554100", "G553100"],
4
14
  Ei: ["E111100"],
15
+ Eiweiß: ["E113100"],
16
+ Erbsen: ["G760200", "G760100"],
5
17
  Essig: [
6
18
  "R122000",
7
19
  "R121000",
8
20
  "R123100"
9
21
  ],
22
+ Fenchel: ["G430100"],
23
+ Frischkäse: ["M710800", "M710700"],
24
+ "Gehackte Tomaten": ["G560900"],
25
+ Grieß: ["C219300", "C218000"],
26
+ "Grüne Bohnen": ["G710100"],
27
+ Gulasch: ["U151100"],
28
+ Hackfleisch: [
29
+ "U040100",
30
+ "U010100",
31
+ "U020100"
32
+ ],
10
33
  Hefe: ["R459000", "R458000"],
34
+ Hühnchen: [
35
+ "V416100",
36
+ "V4A6100",
37
+ "V413000"
38
+ ],
39
+ Hüttenkäse: ["M711300", "M711100"],
40
+ Ingwerpulver: ["R_000024"],
41
+ Jasminreis: ["C352000"],
42
+ Joghurt: [
43
+ "M141300",
44
+ "M141200",
45
+ "M141100"
46
+ ],
47
+ Ketchup: ["R141100"],
48
+ Kirsche: ["F211100", "F212100"],
49
+ Knoblauchzehe: ["G490100"],
50
+ Kochschinken: ["W424000"],
51
+ Kohl: [
52
+ "G342100",
53
+ "G341100",
54
+ "G343100",
55
+ "G344100"
56
+ ],
57
+ Kokosraspel: ["H150400"],
58
+ Koriander: ["G_000001", "R_000006"],
59
+ Kresse: ["G280100"],
60
+ Kürbis: ["G581000", "G581100"],
61
+ Magerquark: ["M713100"],
62
+ Mais: [
63
+ "G570100",
64
+ "G570902",
65
+ "C341000"
66
+ ],
67
+ Maiskörner: ["G570902", "G570100"],
11
68
  Margarine: ["Q400000", "Q481000"],
12
69
  Mehl: [
13
70
  "C214100",
@@ -24,21 +81,82 @@ const meanings = {
24
81
  "C234100",
25
82
  "C234200"
26
83
  ],
84
+ Melone: [
85
+ "F533100",
86
+ "F532100",
87
+ "F535100"
88
+ ],
27
89
  Milch: ["M111300"],
90
+ Naturjoghurt: ["M141300", "M141200"],
91
+ Naturreis: ["C351000"],
92
+ Nudeln: [
93
+ "E401000",
94
+ "E432000",
95
+ "E510000"
96
+ ],
97
+ "Nudeln gekocht": [
98
+ "E401032",
99
+ "E432032",
100
+ "E500032"
101
+ ],
28
102
  Öl: [
29
103
  "Q180000",
30
104
  "Q320000",
31
105
  "Q120000"
32
106
  ],
107
+ Paprika: [
108
+ "G543100",
109
+ "G542100",
110
+ "G541100"
111
+ ],
112
+ Petersilie: ["G250100"],
113
+ Pilze: ["K701100", "K750100"],
33
114
  Quark: [
34
115
  "M713100",
35
116
  "M713300",
36
117
  "M713500"
37
118
  ],
119
+ Reis: ["C352000", "C359000"],
120
+ Rinderhackfleisch: ["U010100"],
121
+ Risottoreis: ["C352000"],
122
+ Rohrzucker: ["S112000"],
123
+ "Rote Bete": ["G613100"],
124
+ "Rote Linsen": ["H730000"],
125
+ Rotwein: ["P2A3000"],
38
126
  Sahne: ["M173800", "M173900"],
127
+ "Salbei getrocknet": ["R_000013"],
39
128
  Salz: ["R111000", "R114000"],
129
+ Schinken: ["W424000", "W442000"],
130
+ Schweinenacken: ["U632100"],
131
+ Sellerie: ["G660100", "G220100"],
132
+ Senfkörner: ["R_000019"],
133
+ Sirup: [
134
+ "S151100",
135
+ "S154000",
136
+ "S151000"
137
+ ],
138
+ Spaghetti: ["E401000"],
139
+ Speck: ["W411300", "W410400"],
140
+ Speisestärke: ["C446000", "C216000"],
40
141
  Stärke: ["C446000", "C216000"],
142
+ Staudensellerie: ["G220100"],
143
+ Tahini: ["Q901000"],
144
+ Tee: ["N630000", "N610100"],
145
+ Traube: [
146
+ "F310100",
147
+ "F311100",
148
+ "F312100"
149
+ ],
150
+ Trockenhefe: ["R458000"],
151
+ Vollkornmehl: ["C211000"],
152
+ Vollkornnudeln: ["E510000"],
153
+ Vollkornreis: ["C351000"],
41
154
  Wasser: ["N110000"],
42
- Zucker: ["S111000"]
155
+ "Weiße Bohnen": ["H739400"],
156
+ Weißwein: ["P210000"],
157
+ Zartbitterschokolade: ["S560000"],
158
+ Zucker: ["S111000"],
159
+ Zwiebel: ["G480100"],
160
+ Zwiebelpulver: ["G480500"]
43
161
  };
44
162
  export { meanings };
package/dist/de.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as Meanings } from "./meanings-DJO-9Ck9.mjs";
2
- import { a as Match, i as SearchOptions, n as FinderOptions, r as Hit, t as Finder } from "./finder-CHsScx2h.mjs";
2
+ import { a as Match, i as SearchOptions, n as FinderOptions, r as Hit, t as Finder } from "./finder-BDvIlKo2.mjs";
3
3
  /** A German finder over `names`, code to name: read once, searched often. */
4
4
  export declare function createFinder(names: Record<string, string>, options?: FinderOptions): Finder;
5
5
  export type { Finder, FinderOptions, Hit, Match, Meanings, SearchOptions };
package/dist/de.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createFinder$1 } from "./finder-yEvLck_3.mjs";
1
+ import { t as createFinder$1 } from "./finder-Dy0IOqpK.mjs";
2
2
  // src/de/language.ts
3
3
  const LETTERS = {
4
4
  ß: "ss",
@@ -6,13 +6,57 @@ const LETTERS = {
6
6
  ö: "oe",
7
7
  ü: "ue"
8
8
  };
9
+ const PLURALS = [
10
+ "en",
11
+ "e",
12
+ "n",
13
+ "s"
14
+ ];
15
+ const UMLAUT_PLURALS = [["nuesse", "nuss"], ["aepfel", "apfel"]];
16
+ function cut(word) {
17
+ const ending = PLURALS.find((end) => word.endsWith(end) && word.length - end.length >= 4);
18
+ return ending ? word.slice(0, -ending.length) : word;
19
+ }
9
20
  const german = {
10
21
  locale: "de-DE",
11
- spell: (text) => text.replace(/[ßäöü]/g, (char) => LETTERS[char] ?? char),
12
- same: /* @__PURE__ */ new Map([["typ", "type"]]),
22
+ spell: (text) => text.replace(/[ßäöü]/g, (char) => LETTERS[char] ?? char).normalize("NFD").replace(/\p{M}/gu, "").normalize("NFC"),
23
+ same: /* @__PURE__ */ new Map([
24
+ ["typ", "type"],
25
+ ["brokkoli", "broccoli"],
26
+ ["dose", "konserve"],
27
+ ["majonaese", "mayonnaise"]
28
+ ]),
13
29
  compounds: {
14
30
  endings: ["frei"],
15
31
  units: ["buchweizen"]
32
+ },
33
+ dish: "mit",
34
+ preparations: [
35
+ "roh",
36
+ "gekocht",
37
+ "gebraten",
38
+ "gedünstet",
39
+ "gedämpft",
40
+ "gebacken",
41
+ "gegrillt",
42
+ "geschmort",
43
+ "frittiert",
44
+ "pochiert",
45
+ "überbacken",
46
+ "geröstet",
47
+ "getrocknet",
48
+ "geräuchert",
49
+ "konserve",
50
+ "tiefgefroren",
51
+ "gemahlen",
52
+ "püriert",
53
+ "blanchiert"
54
+ ],
55
+ stem: (word) => {
56
+ const umlaut = UMLAUT_PLURALS.find(([plural]) => word.endsWith(plural));
57
+ let stem = umlaut ? word.slice(0, -umlaut[0].length) + umlaut[1] : word;
58
+ for (let shorter = cut(stem); shorter !== stem; shorter = cut(stem)) stem = shorter;
59
+ return stem;
16
60
  }
17
61
  };
18
62
  // src/de/index.ts
package/dist/en.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as Meanings } from "./meanings-DJO-9Ck9.mjs";
2
- import { a as Match, i as SearchOptions, n as FinderOptions, r as Hit, t as Finder } from "./finder-CHsScx2h.mjs";
2
+ import { a as Match, i as SearchOptions, n as FinderOptions, r as Hit, t as Finder } from "./finder-BDvIlKo2.mjs";
3
3
  /** An English finder over `names`, code to name: read once, searched often. */
4
4
  export declare function createFinder(names: Record<string, string>, options?: FinderOptions): Finder;
5
5
  export type { Finder, FinderOptions, Hit, Match, Meanings, SearchOptions };
package/dist/en.mjs CHANGED
@@ -1,9 +1,32 @@
1
- import { t as createFinder$1 } from "./finder-yEvLck_3.mjs";
1
+ import { t as createFinder$1 } from "./finder-Dy0IOqpK.mjs";
2
2
  // src/en/language.ts
3
3
  const english = {
4
4
  locale: "en",
5
5
  spell: (text) => text.normalize("NFD").replace(/\p{M}/gu, "").normalize("NFC"),
6
- same: /* @__PURE__ */ new Map()
6
+ same: /* @__PURE__ */ new Map(),
7
+ dish: "with",
8
+ preparations: [
9
+ "raw",
10
+ "cooked",
11
+ "boiled",
12
+ "fried",
13
+ "stewed",
14
+ "steamed",
15
+ "baked",
16
+ "grilled",
17
+ "braised",
18
+ "roasted",
19
+ "dried",
20
+ "frozen",
21
+ "ground"
22
+ ],
23
+ stem: (word) => {
24
+ if (word.length > 4 && word.endsWith("ies")) return `${word.slice(0, -3)}y`;
25
+ if (word.length > 4 && word.endsWith("oes")) return word.slice(0, -2);
26
+ if (word.length > 4 && word.endsWith("oe")) return word.slice(0, -1);
27
+ if (/(ss|us|is)$/.test(word)) return word;
28
+ return word.length > 3 && word.endsWith("s") ? word.slice(0, -1) : word;
29
+ }
7
30
  };
8
31
  // src/en/index.ts
9
32
  /** An English finder over `names`, code to name: read once, searched often. */
@@ -1,10 +1,11 @@
1
1
  import { t as Meanings } from "./meanings-DJO-9Ck9.mjs";
2
2
  /**
3
3
  * How a hit matched the query, best first: the whole name, its start, its words, its words with a
4
- * word of the query as the last part of a compound ("Butter" in "Süßrahmbutter"), or some words of
5
- * the query only.
4
+ * word of the query as the last part of a compound ("Butter" in "Süßrahmbutter"), its words with the
5
+ * last word of the query still being typed ("sulta" for "Sultanine"), some words of the query only,
6
+ * or, when nothing else is found, a mistyped word read as the nearest known one.
6
7
  */
7
- declare const MATCHES: readonly ["exact", "prefix", "words", "compound", "partial"];
8
+ declare const MATCHES: readonly ["exact", "prefix", "words", "compound", "start", "partial", "fuzzy"];
8
9
  type Match = (typeof MATCHES)[number];
9
10
  type Hit = {
10
11
  code: string;
@@ -0,0 +1,433 @@
1
+ // src/compounds.ts
2
+ /**
3
+ * The words a German compound ends with: "Roggenvollkornbrot" is a "Vollkornbrot" and a "Brot".
4
+ */
5
+ function heads(word, reading) {
6
+ const { known, units, found } = reading;
7
+ const cached = found.get(word);
8
+ if (cached) return cached;
9
+ const candidates = [];
10
+ for (let cut = 2; cut < word.length - 1; cut++) {
11
+ const stem = word.slice(0, cut);
12
+ const head = word.slice(cut);
13
+ if (!known.has(head) || !/[aeiouy]/.test(stem)) continue;
14
+ if (units.some((unit) => splits(word, unit, cut))) continue;
15
+ candidates.push({
16
+ head,
17
+ sure: known.has(stem)
18
+ });
19
+ }
20
+ const sure = candidates.filter((candidate) => candidate.sure);
21
+ const leads = sure.length > 0 ? sure : candidates.slice(0, 1);
22
+ const result = candidates.map(({ head }) => head).filter((head) => leads.every((lead) => lead.head === head || (lead.head.length > head.length ? heads(lead.head, reading).includes(head) : heads(head, reading).includes(lead.head))));
23
+ found.set(word, result);
24
+ return result;
25
+ }
26
+ function splits(word, unit, cut) {
27
+ return word.slice(Math.max(0, cut - unit.length + 1), cut + unit.length - 1).includes(unit);
28
+ }
29
+ // src/words.ts
30
+ /** The words of a name or a query as they are compared; a decimal point reads as a comma. */
31
+ function words(text, language) {
32
+ return (language.spell(text.normalize("NFC").toLocaleLowerCase(language.locale)).match(/\d+(?:[.,]\d+)?|\p{L}+|\p{N}|%/gu) ?? []).map((word) => language.same.get(word) ?? word.replace(".", ","));
33
+ }
34
+ // src/meanings.ts
35
+ /** The meanings of every code, the first source winning a word. */
36
+ function readMeanings(sources, language) {
37
+ const taken = /* @__PURE__ */ new Set();
38
+ const byCode = /* @__PURE__ */ new Map();
39
+ for (const source of sources) for (const [key, codes] of Object.entries(source)) {
40
+ const read = words(key, language);
41
+ const id = read.join(" ");
42
+ if (taken.has(id)) continue;
43
+ taken.add(id);
44
+ codes.forEach((code, order) => {
45
+ byCode.set(code, [...byCode.get(code) ?? [], {
46
+ words: read,
47
+ order
48
+ }]);
49
+ });
50
+ }
51
+ return byCode;
52
+ }
53
+ // src/spelling.ts
54
+ /**
55
+ * How a hit matched the query, best first: the whole name, its start, its words, its words with a
56
+ * word of the query as the last part of a compound ("Butter" in "Süßrahmbutter"), its words with the
57
+ * last word of the query still being typed ("sulta" for "Sultanine"), some words of the query only,
58
+ * or, when nothing else is found, a mistyped word read as the nearest known one.
59
+ */
60
+ const MATCHES = [
61
+ "exact",
62
+ "prefix",
63
+ "words",
64
+ "compound",
65
+ "start",
66
+ "partial",
67
+ "fuzzy"
68
+ ];
69
+ /** A word as it is: for languages without a `stem`. */
70
+ const same = (word) => word;
71
+ function spell(words, stem = same) {
72
+ const ends = /* @__PURE__ */ new Set();
73
+ const spans = /* @__PURE__ */ new Set();
74
+ let end = 0;
75
+ for (let start = 0; start < words.length; start++) {
76
+ end += words[start].length;
77
+ ends.add(end);
78
+ for (let last = start + 1; last <= words.length; last++) {
79
+ const span = words.slice(start, last).join("");
80
+ spans.add(span);
81
+ spans.add(stem(span));
82
+ }
83
+ }
84
+ return {
85
+ words,
86
+ whole: words.join(""),
87
+ ends,
88
+ spans
89
+ };
90
+ }
91
+ /**
92
+ * The index of the match in `MATCHES`, -1 for none. `endsOf` gives the words a word of a name ends
93
+ * with, if the language builds compounds.
94
+ */
95
+ function rankOf(asked, name, endsOf, stem = same) {
96
+ const wanted = asked.join("");
97
+ if (!wanted) return -1;
98
+ if (name.whole === wanted) return 0;
99
+ if (name.ends.has(wanted.length) && name.whole.startsWith(wanted)) return 1;
100
+ if (startsAsStem(asked, name, stem)) return 1;
101
+ if (covers(asked, name.spans, stem)) return 2;
102
+ if (!endsOf) return -1;
103
+ return covers(asked, piecesOf(name, endsOf, stem), stem) ? 3 : -1;
104
+ }
105
+ function startsAsStem(asked, name, stem) {
106
+ const wanted = asked.join("");
107
+ const whole = stem(wanted);
108
+ const byWord = asked.map(stem).join("");
109
+ let lead = "";
110
+ let leadByWord = "";
111
+ for (const word of name.words) {
112
+ lead += word;
113
+ leadByWord += stem(word);
114
+ if (lead.length > wanted.length + 2) return false;
115
+ if (stem(lead) === whole || leadByWord === byWord) return true;
116
+ }
117
+ return false;
118
+ }
119
+ /**
120
+ * How far a name is from what is being typed, when the last word of the query is unfinished: the
121
+ * letters before it in the name and the letters still to type. The other words are whole words of
122
+ * the name, as in `rankOf`. Undefined when the name does not hold it so.
123
+ */
124
+ function startOf(asked, name, endsOf, stem = same) {
125
+ const last = asked.at(-1);
126
+ if (!last || !/^(\p{L}{3,}|\p{N}{2,})$/u.test(last)) return void 0;
127
+ const front = asked.slice(0, -1);
128
+ if (!covers(front, piecesOf(name, endsOf, stem), stem)) return void 0;
129
+ const lead = front.join("").length;
130
+ let nearest;
131
+ for (const [piece, places] of placesOf(name, endsOf, stem)) {
132
+ if (!piece.startsWith(last)) continue;
133
+ for (const at of places) {
134
+ const away = Math.abs(at - lead) + piece.length - last.length;
135
+ if (nearest === void 0 || away < nearest) nearest = away;
136
+ }
137
+ }
138
+ return nearest;
139
+ }
140
+ function placesOf(name, endsOf, stem = same) {
141
+ if (name.places) return name.places;
142
+ const places = /* @__PURE__ */ new Map();
143
+ const add = (piece, at) => {
144
+ places.set(piece, [...places.get(piece) ?? [], at]);
145
+ if (stem(piece) !== piece) places.set(stem(piece), [...places.get(stem(piece)) ?? [], at]);
146
+ };
147
+ let at = 0;
148
+ for (let start = 0; start < name.words.length; start++) {
149
+ const word = name.words[start];
150
+ let run = "";
151
+ for (const next of name.words.slice(start)) {
152
+ run += next;
153
+ add(run, at);
154
+ }
155
+ for (const head of endsOf?.(word) ?? []) add(head, at + word.length - head.length);
156
+ at += word.length;
157
+ }
158
+ name.places = places;
159
+ return places;
160
+ }
161
+ function ask(words, endsOf) {
162
+ return {
163
+ words,
164
+ runs: words.map((_, end) => words.map((_, start) => words.slice(start, end + 1).join(""))),
165
+ tails: words.map((word) => endsOf?.(word) ?? [])
166
+ };
167
+ }
168
+ /**
169
+ * How much of the query a name holds when it does not hold all of it: the letters found, and the
170
+ * words missed. A word of the query may be found by its last part: "Rindergelatine" is a
171
+ * "Gelatine" with "rinder" missed. Longer words carry more meaning, so letters count, not words.
172
+ */
173
+ function partialOf(asked, name, endsOf, stem = same) {
174
+ const pieces = piecesOf(name, endsOf, stem);
175
+ const best = [{
176
+ covered: 0,
177
+ missed: []
178
+ }];
179
+ for (let end = 1; end <= asked.words.length; end++) {
180
+ const word = asked.words[end - 1];
181
+ const before = best[end - 1];
182
+ const options = [{
183
+ covered: before.covered,
184
+ missed: [...before.missed, word]
185
+ }];
186
+ for (let start = 0; start < end; start++) {
187
+ const run = asked.runs[end - 1][start];
188
+ if (!pieces.has(run) && !pieces.has(stem(run))) continue;
189
+ options.push({
190
+ covered: best[start].covered + run.length,
191
+ missed: best[start].missed
192
+ });
193
+ }
194
+ for (const tail of asked.tails[end - 1]) {
195
+ if (!pieces.has(tail) || tail.length * 2 < word.length) continue;
196
+ const stem = word.slice(0, -tail.length);
197
+ options.push({
198
+ covered: before.covered + tail.length,
199
+ missed: [...before.missed, stem]
200
+ });
201
+ }
202
+ best[end] = options.reduce((a, b) => b.covered > a.covered ? b : a);
203
+ }
204
+ const found = best[asked.words.length];
205
+ return found.covered > 0 ? found : void 0;
206
+ }
207
+ function piecesOf(name, endsOf, stem = same) {
208
+ if (!endsOf) return name.spans;
209
+ name.compounds ??= /* @__PURE__ */ new Set([...name.spans, ...name.words.flatMap((word) => endsOf(word).flatMap((head) => [head, stem(head)]))]);
210
+ return name.compounds;
211
+ }
212
+ function covers(asked, spans, stem) {
213
+ const reached = [true];
214
+ for (let end = 1; end <= asked.length; end++) reached[end] = asked.slice(0, end).some((_, start) => {
215
+ if (reached[start] !== true) return false;
216
+ const run = asked.slice(start, end).join("");
217
+ return spans.has(run) || spans.has(stem(run));
218
+ });
219
+ return reached[asked.length] === true;
220
+ }
221
+ /**
222
+ * Letters to change, add, drop or swap with a neighbour to turn `a` into `b`; `limit + 1` as soon as
223
+ * it is clear that more than `limit` are needed.
224
+ */
225
+ function distance(a, b, limit) {
226
+ if (Math.abs(a.length - b.length) > limit) return limit + 1;
227
+ let before = [];
228
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
229
+ for (let i = 1; i <= a.length; i++) {
230
+ const current = [i];
231
+ let smallest = i;
232
+ for (let j = 1; j <= b.length; j++) {
233
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
234
+ let value = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
235
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) value = Math.min(value, before[j - 2] + 1);
236
+ current[j] = value;
237
+ smallest = Math.min(smallest, value);
238
+ }
239
+ if (smallest > limit) return limit + 1;
240
+ before = previous;
241
+ previous = current;
242
+ }
243
+ return Math.min(previous[b.length], limit + 1);
244
+ }
245
+ // src/variants.ts
246
+ const ALTERNATIVES = /[^\s,()/]*\/[^\s,()]*/g;
247
+ /**
248
+ * A name and its spellings with the BLS slash synonyms, "Weizenbrot/Weißbrot", "mit
249
+ * Nugat/Nougat/Noisette": each alternative replaces only its own word, a shorter group keeps its
250
+ * last alternative.
251
+ */
252
+ function variants(name) {
253
+ const groups = name.match(ALTERNATIVES) ?? [];
254
+ const count = Math.max(0, ...groups.map((group) => group.split("/").length));
255
+ return [name, ...Array.from({ length: count }, (_, index) => name.replace(ALTERNATIVES, (group) => {
256
+ const alternatives = group.split("/");
257
+ return alternatives[Math.min(index, alternatives.length - 1)];
258
+ }))];
259
+ }
260
+ // src/finder.ts
261
+ /** Reads every name once; every search reuses it. `names` is code to name. */
262
+ function createFinder(names, language, options = {}) {
263
+ const stem = language.stem ?? same;
264
+ const foods = Object.entries(names).map(([code, name]) => ({
265
+ code,
266
+ name,
267
+ spellings: variants(name).map((variant) => spell(words(variant, language), stem))
268
+ }));
269
+ const byCode = new Map(foods.map((food) => [food.code, food]));
270
+ const endsOf = language.compounds && compoundsOf(foods, language.compounds, stem);
271
+ const meant = readMeanings(options.meanings ?? [], language);
272
+ for (const food of foods) for (const { words: read, order } of meant.get(food.code) ?? []) food.spellings.push({
273
+ ...spell(read, stem),
274
+ meant: order
275
+ });
276
+ function search(query, options = {}) {
277
+ const asked = words(query, language);
278
+ const scope = foods.filter(({ code }) => !options.group || code.startsWith(options.group));
279
+ let found = find(asked, scope);
280
+ if (found.length === 0) found = mistyped(asked, scope);
281
+ return found.slice(0, options.limit).map(({ code, name, rank, meant, missed }) => ({
282
+ code,
283
+ name,
284
+ match: MATCHES[rank],
285
+ meant: meant !== NOT_MEANT,
286
+ missed
287
+ }));
288
+ }
289
+ function find(asked, scope) {
290
+ const wanted = asked.join("").length;
291
+ const hits = collect(scope, (spelled) => {
292
+ const rank = rankOf(asked, spelled, endsOf, stem);
293
+ return rank < 0 ? void 0 : {
294
+ rank,
295
+ covered: wanted,
296
+ missed: []
297
+ };
298
+ }).sort(order);
299
+ const byPreparation = hits.some((hit) => hit.meant !== NOT_MEANT) ? [] : prepared(asked, scope);
300
+ const meant = byPreparation.filter((hit) => hit.meant !== NOT_MEANT);
301
+ if (meant.length > 0) return unique([...meant, ...hits]);
302
+ if (hits.length > 0) return hits;
303
+ if (byPreparation.length > 0) return byPreparation;
304
+ const started = collect(scope, (spelled) => {
305
+ const away = startOf(asked, spelled, endsOf, stem);
306
+ return away === void 0 ? void 0 : {
307
+ rank: START,
308
+ covered: wanted,
309
+ missed: [],
310
+ away
311
+ };
312
+ });
313
+ if (started.length > 0) return started.sort(order);
314
+ return partials(asked, scope).sort(order);
315
+ }
316
+ function mistyped(asked, scope) {
317
+ const readings = asked.map((word) => vocabulary().has(word) || vocabulary().has(stem(word)) ? [word] : nearest(word));
318
+ if (readings.every((options, index) => options.length === 1 && options[0] === asked[index])) return [];
319
+ return unique(readings.reduce((all, options) => all.flatMap((query) => (options.length > 0 ? options : [""]).map((word) => [...query, word])), [[]]).slice(0, 9).flatMap((query) => find(query.filter(Boolean), scope))).map((hit) => ({
320
+ ...hit,
321
+ rank: FUZZY
322
+ }));
323
+ }
324
+ let known;
325
+ const vocabulary = () => known ??= new Set(foods.flatMap((food) => food.spellings.flatMap((spelled) => spelled.words.filter((word) => /^\p{L}+$/u.test(word)))));
326
+ function nearest(word) {
327
+ if (word.length < 5 || !/^\p{L}+$/u.test(word)) return [];
328
+ const limit = word.length >= 7 ? 2 : 1;
329
+ let best = limit + 1;
330
+ let found = [];
331
+ for (const candidate of vocabulary()) {
332
+ const away = distance(word, candidate, Math.min(best, limit));
333
+ if (away < best) {
334
+ best = away;
335
+ found = [candidate];
336
+ } else if (away === best && away <= limit) found.push(candidate);
337
+ }
338
+ return best <= limit ? found.slice(0, 3) : [];
339
+ }
340
+ function partials(asked, scope) {
341
+ const read = ask(asked, endsOf);
342
+ const food = asked.filter((word) => !isPreparation(word) && word.length >= 4);
343
+ return collect(scope, (spelled) => {
344
+ const partial = partialOf(read, spelled, endsOf, stem);
345
+ if (!partial) return void 0;
346
+ if (food.length > 0 && food.every((word) => partial.missed.includes(word))) return void 0;
347
+ return {
348
+ rank: PARTIAL,
349
+ ...partial
350
+ };
351
+ });
352
+ }
353
+ const order = (a, b) => better(a, b) || a.name.localeCompare(b.name, language.locale) || a.code.localeCompare(b.code);
354
+ const preparations = new Set((language.preparations ?? []).map((word) => stem(words(word, language).join(""))));
355
+ const dish = language.dish && words(language.dish, language)[0];
356
+ const isPreparation = (word) => preparations.has(stem(word)) || preparations.has(stem(word.replace(/(er|es|em)$/, "")));
357
+ function prepared(asked, scope) {
358
+ const preparation = asked.filter(isPreparation);
359
+ const food = asked.filter((word) => !isPreparation(word));
360
+ if (preparation.length === 0 || food.length === 0) return [];
361
+ const wanted = food.join("").length;
362
+ const plain = collect(scope, (spelled) => {
363
+ const rank = rankOf(food, spelled, endsOf, stem);
364
+ return rank < 0 ? void 0 : {
365
+ rank,
366
+ covered: wanted,
367
+ missed: preparation
368
+ };
369
+ }).sort(order);
370
+ if (plain.length === 0) return [];
371
+ const meant = plain.filter((hit) => hit.meant !== NOT_MEANT);
372
+ const seeds = meant.length > 0 ? meant : plain.slice(0, 1);
373
+ const core = (code) => (byCode.get(code)?.spellings[0]?.words ?? []).filter((word) => !isPreparation(word));
374
+ return unique([...seeds.flatMap((seed) => {
375
+ const kernel = core(seed.code);
376
+ return collect(scope, (spelled) => {
377
+ const holds = kernel.every((word) => spelled.words.includes(word));
378
+ if (dish !== void 0 && spelled.words.includes(dish)) return void 0;
379
+ if (!holds || rankOf(preparation, spelled, endsOf, stem) < 0) return void 0;
380
+ return {
381
+ rank: seed.rank,
382
+ covered: asked.join("").length,
383
+ missed: []
384
+ };
385
+ }).sort(order).map((variant) => ({
386
+ ...variant,
387
+ meant: seed.meant
388
+ }));
389
+ }), ...plain.map((hit) => ({
390
+ ...hit,
391
+ rank: PARTIAL
392
+ }))]);
393
+ }
394
+ return { search };
395
+ }
396
+ const START = MATCHES.indexOf("start");
397
+ const PARTIAL = MATCHES.indexOf("partial");
398
+ const FUZZY = MATCHES.indexOf("fuzzy");
399
+ const NOT_MEANT = Infinity;
400
+ const better = (a, b) => a.rank - b.rank || b.covered - a.covered || (a.away ?? 0) - (b.away ?? 0) || a.meant - b.meant || a.length - b.length;
401
+ function unique(hits) {
402
+ const seen = /* @__PURE__ */ new Set();
403
+ return hits.filter(({ code }) => !seen.has(code) && seen.add(code));
404
+ }
405
+ function collect(foods, read) {
406
+ return foods.flatMap(({ code, name, spellings }) => {
407
+ const found = spellings.flatMap((spelled) => {
408
+ const result = read(spelled);
409
+ if (!result) return [];
410
+ return [{
411
+ ...result,
412
+ meant: spelled.meant ?? NOT_MEANT,
413
+ length: spelled.whole.length
414
+ }];
415
+ }).sort(better)[0];
416
+ return found ? [{
417
+ code,
418
+ name,
419
+ ...found
420
+ }] : [];
421
+ });
422
+ }
423
+ function compoundsOf(foods, rules, stem) {
424
+ const known = new Set(foods.flatMap((food) => food.spellings.flatMap((spelled) => spelled.words.flatMap((word) => [word, stem(word)]))));
425
+ for (const ending of rules.endings) known.add(ending);
426
+ const reading = {
427
+ known,
428
+ units: rules.units,
429
+ found: /* @__PURE__ */ new Map()
430
+ };
431
+ return (word) => heads(word, reading);
432
+ }
433
+ export { createFinder as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thereforejs/food-finder",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "Find foods of @thereforejs/foods by what people type: search, aliases and language rules, loaded per language",
5
5
  "keywords": [
6
6
  "bls",
@@ -37,7 +37,7 @@
37
37
  "provenance": true
38
38
  },
39
39
  "devDependencies": {
40
- "@thereforejs/foods": "^0.0.1",
40
+ "@thereforejs/foods": "^0.0.3",
41
41
  "@types/node": "^26.6.5",
42
42
  "fast-check": "^4.10.2",
43
43
  "typescript": "^7.0.2",
@@ -1,244 +0,0 @@
1
- // src/compounds.ts
2
- /**
3
- * The words a German compound ends with: "Roggenvollkornbrot" is a "Vollkornbrot" and a "Brot".
4
- */
5
- function heads(word, reading) {
6
- const { known, units, found } = reading;
7
- const cached = found.get(word);
8
- if (cached) return cached;
9
- const candidates = [];
10
- for (let cut = 2; cut < word.length - 1; cut++) {
11
- const stem = word.slice(0, cut);
12
- const head = word.slice(cut);
13
- if (!known.has(head) || !/[aeiouy]/.test(stem)) continue;
14
- if (units.some((unit) => splits(word, unit, cut))) continue;
15
- candidates.push({
16
- head,
17
- sure: known.has(stem)
18
- });
19
- }
20
- const sure = candidates.filter((candidate) => candidate.sure);
21
- const leads = sure.length > 0 ? sure : candidates.slice(0, 1);
22
- const result = candidates.map(({ head }) => head).filter((head) => leads.every((lead) => lead.head === head || (lead.head.length > head.length ? heads(lead.head, reading).includes(head) : heads(head, reading).includes(lead.head))));
23
- found.set(word, result);
24
- return result;
25
- }
26
- function splits(word, unit, cut) {
27
- return word.slice(Math.max(0, cut - unit.length + 1), cut + unit.length - 1).includes(unit);
28
- }
29
- // src/words.ts
30
- /** The words of a name or a query as they are compared; a decimal point reads as a comma. */
31
- function words(text, language) {
32
- return (language.spell(text.normalize("NFC").toLocaleLowerCase(language.locale)).match(/\d+(?:[.,]\d+)?|\p{L}+|\p{N}|%/gu) ?? []).map((word) => language.same.get(word) ?? word.replace(".", ","));
33
- }
34
- // src/meanings.ts
35
- /** The meanings of every code, the first source winning a word. */
36
- function readMeanings(sources, language) {
37
- const taken = /* @__PURE__ */ new Set();
38
- const byCode = /* @__PURE__ */ new Map();
39
- for (const source of sources) for (const [key, codes] of Object.entries(source)) {
40
- const read = words(key, language);
41
- const id = read.join(" ");
42
- if (taken.has(id)) continue;
43
- taken.add(id);
44
- codes.forEach((code, order) => {
45
- byCode.set(code, [...byCode.get(code) ?? [], {
46
- words: read,
47
- order
48
- }]);
49
- });
50
- }
51
- return byCode;
52
- }
53
- // src/spelling.ts
54
- /**
55
- * How a hit matched the query, best first: the whole name, its start, its words, its words with a
56
- * word of the query as the last part of a compound ("Butter" in "Süßrahmbutter"), or some words of
57
- * the query only.
58
- */
59
- const MATCHES = [
60
- "exact",
61
- "prefix",
62
- "words",
63
- "compound",
64
- "partial"
65
- ];
66
- function spell(words) {
67
- const ends = /* @__PURE__ */ new Set();
68
- const spans = /* @__PURE__ */ new Set();
69
- let end = 0;
70
- for (let start = 0; start < words.length; start++) {
71
- end += words[start].length;
72
- ends.add(end);
73
- for (let last = start + 1; last <= words.length; last++) spans.add(words.slice(start, last).join(""));
74
- }
75
- return {
76
- words,
77
- whole: words.join(""),
78
- ends,
79
- spans
80
- };
81
- }
82
- /**
83
- * The index of the match in `MATCHES`, -1 for none. `endsOf` gives the words a word of a name ends
84
- * with, if the language builds compounds.
85
- */
86
- function rankOf(asked, name, endsOf) {
87
- const wanted = asked.join("");
88
- if (!wanted) return -1;
89
- if (name.whole === wanted) return 0;
90
- if (name.ends.has(wanted.length) && name.whole.startsWith(wanted)) return 1;
91
- if (covers(asked, name.spans)) return 2;
92
- if (!endsOf) return -1;
93
- return covers(asked, piecesOf(name, endsOf)) ? 3 : -1;
94
- }
95
- function ask(words, endsOf) {
96
- return {
97
- words,
98
- runs: words.map((_, end) => words.map((_, start) => words.slice(start, end + 1).join(""))),
99
- tails: words.map((word) => endsOf?.(word) ?? [])
100
- };
101
- }
102
- /**
103
- * How much of the query a name holds when it does not hold all of it: the letters found, and the
104
- * words missed. A word of the query may be found by its last part: "Rindergelatine" is a
105
- * "Gelatine" with "rinder" missed. Longer words carry more meaning, so letters count, not words.
106
- */
107
- function partialOf(asked, name, endsOf) {
108
- const pieces = piecesOf(name, endsOf);
109
- const best = [{
110
- covered: 0,
111
- missed: []
112
- }];
113
- for (let end = 1; end <= asked.words.length; end++) {
114
- const word = asked.words[end - 1];
115
- const before = best[end - 1];
116
- const options = [{
117
- covered: before.covered,
118
- missed: [...before.missed, word]
119
- }];
120
- for (let start = 0; start < end; start++) {
121
- const run = asked.runs[end - 1][start];
122
- if (!pieces.has(run)) continue;
123
- options.push({
124
- covered: best[start].covered + run.length,
125
- missed: best[start].missed
126
- });
127
- }
128
- for (const tail of asked.tails[end - 1]) {
129
- if (!pieces.has(tail) || tail.length * 2 < word.length) continue;
130
- const stem = word.slice(0, -tail.length);
131
- options.push({
132
- covered: before.covered + tail.length,
133
- missed: [...before.missed, stem]
134
- });
135
- }
136
- best[end] = options.reduce((a, b) => b.covered > a.covered ? b : a);
137
- }
138
- const found = best[asked.words.length];
139
- return found.covered > 0 ? found : void 0;
140
- }
141
- function piecesOf(name, endsOf) {
142
- if (!endsOf) return name.spans;
143
- name.compounds ??= /* @__PURE__ */ new Set([...name.spans, ...name.words.flatMap((word) => endsOf(word))]);
144
- return name.compounds;
145
- }
146
- function covers(asked, spans) {
147
- const reached = [true];
148
- for (let end = 1; end <= asked.length; end++) reached[end] = asked.slice(0, end).some((_, start) => reached[start] === true && spans.has(asked.slice(start, end).join("")));
149
- return reached[asked.length] === true;
150
- }
151
- // src/variants.ts
152
- const ALTERNATIVES = /[^\s,()/]*\/[^\s,()]*/g;
153
- /**
154
- * A name and its spellings with the BLS slash synonyms, "Weizenbrot/Weißbrot", "mit
155
- * Nugat/Nougat/Noisette": each alternative replaces only its own word, a shorter group keeps its
156
- * last alternative.
157
- */
158
- function variants(name) {
159
- const groups = name.match(ALTERNATIVES) ?? [];
160
- const count = Math.max(0, ...groups.map((group) => group.split("/").length));
161
- return [name, ...Array.from({ length: count }, (_, index) => name.replace(ALTERNATIVES, (group) => {
162
- const alternatives = group.split("/");
163
- return alternatives[Math.min(index, alternatives.length - 1)];
164
- }))];
165
- }
166
- // src/finder.ts
167
- /** Reads every name once; every search reuses it. `names` is code to name. */
168
- function createFinder(names, language, options = {}) {
169
- const foods = Object.entries(names).map(([code, name]) => ({
170
- code,
171
- name,
172
- spellings: variants(name).map((variant) => spell(words(variant, language)))
173
- }));
174
- const endsOf = language.compounds && compoundsOf(foods, language.compounds);
175
- const meant = readMeanings(options.meanings ?? [], language);
176
- for (const food of foods) for (const { words: read, order } of meant.get(food.code) ?? []) food.spellings.push({
177
- ...spell(read),
178
- meant: order
179
- });
180
- function search(query, options = {}) {
181
- const asked = words(query, language);
182
- const wanted = asked.join("").length;
183
- const scope = foods.filter(({ code }) => !options.group || code.startsWith(options.group));
184
- let hits = collect(scope, (spelled) => {
185
- const rank = rankOf(asked, spelled, endsOf);
186
- return rank < 0 ? void 0 : {
187
- rank,
188
- covered: wanted,
189
- missed: []
190
- };
191
- });
192
- if (hits.length === 0) {
193
- const read = ask(asked, endsOf);
194
- hits = collect(scope, (spelled) => {
195
- const partial = partialOf(read, spelled, endsOf);
196
- return partial && {
197
- rank: PARTIAL,
198
- ...partial
199
- };
200
- });
201
- }
202
- hits.sort((a, b) => better(a, b) || a.name.localeCompare(b.name, language.locale) || a.code.localeCompare(b.code));
203
- return hits.slice(0, options.limit).map(({ code, name, rank, meant, missed }) => ({
204
- code,
205
- name,
206
- match: MATCHES[rank],
207
- meant: meant !== NOT_MEANT,
208
- missed
209
- }));
210
- }
211
- return { search };
212
- }
213
- const PARTIAL = MATCHES.indexOf("partial");
214
- const NOT_MEANT = Infinity;
215
- const better = (a, b) => a.rank - b.rank || b.covered - a.covered || a.meant - b.meant || a.length - b.length;
216
- function collect(foods, read) {
217
- return foods.flatMap(({ code, name, spellings }) => {
218
- const found = spellings.flatMap((spelled) => {
219
- const result = read(spelled);
220
- if (!result) return [];
221
- return [{
222
- ...result,
223
- meant: spelled.meant ?? NOT_MEANT,
224
- length: spelled.whole.length
225
- }];
226
- }).sort(better)[0];
227
- return found ? [{
228
- code,
229
- name,
230
- ...found
231
- }] : [];
232
- });
233
- }
234
- function compoundsOf(foods, rules) {
235
- const known = new Set(foods.flatMap((food) => food.spellings.flatMap((spelled) => spelled.words)));
236
- for (const ending of rules.endings) known.add(ending);
237
- const reading = {
238
- known,
239
- units: rules.units,
240
- found: /* @__PURE__ */ new Map()
241
- };
242
- return (word) => heads(word, reading);
243
- }
244
- export { createFinder as t };