@thereforejs/food-finder 0.0.1 → 0.0.3

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,21 @@ 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
+ - `partial`: only when no name holds the whole query, the names that hold the most of it. A part
53
+ that is only a preparation ("gedünstet") or a short word ("der") is no hit.
54
+ - `fuzzy`: only when nothing else is found, every word no name holds read as its nearest known
55
+ word, one letter off from five letters, two from seven: "Kartofel" finds "Kartoffel",
56
+ "Spagetti gekocht" the cooked pasta. Short words are never read so: "Eis" stays "Eis".
52
57
  - **`meant`**: found through a meaning (below), not the name.
58
+
59
+ A preparation ("gekocht", "gebraten", "Dose") picks the variant of what the other words mean:
60
+ "Spaghetti gekocht" is "Teigwaren eifrei, gekocht", "Ei gekocht" is "Hühnerei gekocht", not
61
+ "Entenei gekocht". Where the food has no such variant, the food itself comes with the preparation
62
+ missed, never another food that merely shares it.
63
+
53
64
  - **`missed`**: the words of the query, as read, that the name does not hold (`partial` only).
54
65
 
55
66
  Options of `search`: `limit` (at most this many hits) and `group` (only codes starting with it, the
@@ -107,23 +118,25 @@ const finder = createFinder(
107
118
 
108
119
  One entry point per language, so a German application holds no English:
109
120
 
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 |
121
+ | Import | Reads |
122
+ | ------------------------------------ | ------------------------------------------------------------------------------------------------ |
123
+ | `@thereforejs/food-finder/de` | German: ß/ä/ö/ü typed as ss/ae/oe/ue, other accents dropped, "Typ" as "Type", plurals, compounds |
124
+ | `@thereforejs/food-finder/en` | English: accents typed without them, plurals |
125
+ | `.../de/meanings`, `.../en/meanings` | the meanings of each language, only when you import them |
115
126
 
116
127
  ## Size
117
128
 
118
- Measured 2026-10-29, an application built with the Vite+ bundler, minified, gzip:
129
+ Measured 2026-11-01 with `vpx scripts/size.ts` after `vp pack`: an application per entry, built with
130
+ the Vite+ bundler, minified, gzip:
119
131
 
120
132
  | Application | App part | Names, loaded on first use |
121
133
  | ------------------------ | -------- | -------------------------- |
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 |
134
+ | `/de` | 3,603 B | 70,882 B |
135
+ | `/de` and `/de/meanings` | 4,789 B | 70,882 B |
136
+ | `/en` | 3,326 B | 69,116 B |
125
137
 
126
- On the 7,108 German names, `createFinder` takes about 65 ms and a search about 10 to 40 ms.
138
+ On the 7,152 German names, `createFinder` takes about 75 to 95 ms (the first call up to 130 ms) and a
139
+ search about 9 to 40 ms; a mistyped one, read word by word, up to about 65 ms.
127
140
 
128
141
  ## License
129
142
 
@@ -1,7 +1,71 @@
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"],
17
+ Essig: [
18
+ "R122000",
19
+ "R121000",
20
+ "R123100"
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
+ ],
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"],
68
+ Margarine: ["Q400000", "Q481000"],
5
69
  Mehl: [
6
70
  "C214100",
7
71
  "C214200",
@@ -17,8 +81,82 @@ const meanings = {
17
81
  "C234100",
18
82
  "C234200"
19
83
  ],
84
+ Melone: [
85
+ "F533100",
86
+ "F532100",
87
+ "F535100"
88
+ ],
20
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
+ ],
102
+ Öl: [
103
+ "Q180000",
104
+ "Q320000",
105
+ "Q120000"
106
+ ],
107
+ Paprika: [
108
+ "G543100",
109
+ "G542100",
110
+ "G541100"
111
+ ],
112
+ Petersilie: ["G250100"],
113
+ Pilze: ["K701100", "K750100"],
114
+ Quark: [
115
+ "M713100",
116
+ "M713300",
117
+ "M713500"
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"],
21
126
  Sahne: ["M173800", "M173900"],
22
- Zucker: ["S111000"]
127
+ "Salbei getrocknet": ["R_000013"],
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"],
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"],
154
+ Wasser: ["N110000"],
155
+ "Weiße Bohnen": ["H739400"],
156
+ Weißwein: ["P210000"],
157
+ Zartbitterschokolade: ["S560000"],
158
+ Zucker: ["S111000"],
159
+ Zwiebel: ["G480100"],
160
+ Zwiebelpulver: ["G480500"]
23
161
  };
24
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-CvhfeMAo.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-Dv8sg_xg.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
@@ -1,3 +1,44 @@
1
1
  // src/en/meanings.ts
2
- const meanings = {};
2
+ const meanings = {
3
+ butter: ["Q630000"],
4
+ cream: ["M173800", "M173900"],
5
+ egg: ["E111100"],
6
+ flour: [
7
+ "C214100",
8
+ "C214200",
9
+ "C213100",
10
+ "C213200",
11
+ "C213500",
12
+ "C223100",
13
+ "C223200",
14
+ "C223300",
15
+ "C223400",
16
+ "C223600",
17
+ "C234000",
18
+ "C234100",
19
+ "C234200"
20
+ ],
21
+ margarine: ["Q400000", "Q481000"],
22
+ milk: ["M111300"],
23
+ oil: [
24
+ "Q180000",
25
+ "Q320000",
26
+ "Q120000"
27
+ ],
28
+ quark: [
29
+ "M713100",
30
+ "M713300",
31
+ "M713500"
32
+ ],
33
+ salt: ["R111000", "R114000"],
34
+ starch: ["C446000", "C216000"],
35
+ sugar: ["S111000"],
36
+ vinegar: [
37
+ "R122000",
38
+ "R121000",
39
+ "R123100"
40
+ ],
41
+ water: ["N110000"],
42
+ yeast: ["R459000", "R458000"]
43
+ };
3
44
  export { meanings };
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-CvhfeMAo.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-Dv8sg_xg.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,10 @@
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"), some words of the
5
+ * query only, or, when nothing else is found, a mistyped word read as the nearest known one.
6
6
  */
7
- declare const MATCHES: readonly ["exact", "prefix", "words", "compound", "partial"];
7
+ declare const MATCHES: readonly ["exact", "prefix", "words", "compound", "partial", "fuzzy"];
8
8
  type Match = (typeof MATCHES)[number];
9
9
  type Hit = {
10
10
  code: string;
@@ -53,24 +53,31 @@ function readMeanings(sources, language) {
53
53
  // src/spelling.ts
54
54
  /**
55
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.
56
+ * word of the query as the last part of a compound ("Butter" in "Süßrahmbutter"), some words of the
57
+ * query only, or, when nothing else is found, a mistyped word read as the nearest known one.
58
58
  */
59
59
  const MATCHES = [
60
60
  "exact",
61
61
  "prefix",
62
62
  "words",
63
63
  "compound",
64
- "partial"
64
+ "partial",
65
+ "fuzzy"
65
66
  ];
66
- function spell(words) {
67
+ /** A word as it is: for languages without a `stem`. */
68
+ const same = (word) => word;
69
+ function spell(words, stem = same) {
67
70
  const ends = /* @__PURE__ */ new Set();
68
71
  const spans = /* @__PURE__ */ new Set();
69
72
  let end = 0;
70
73
  for (let start = 0; start < words.length; start++) {
71
74
  end += words[start].length;
72
75
  ends.add(end);
73
- for (let last = start + 1; last <= words.length; last++) spans.add(words.slice(start, last).join(""));
76
+ for (let last = start + 1; last <= words.length; last++) {
77
+ const span = words.slice(start, last).join("");
78
+ spans.add(span);
79
+ spans.add(stem(span));
80
+ }
74
81
  }
75
82
  return {
76
83
  words,
@@ -83,14 +90,29 @@ function spell(words) {
83
90
  * The index of the match in `MATCHES`, -1 for none. `endsOf` gives the words a word of a name ends
84
91
  * with, if the language builds compounds.
85
92
  */
86
- function rankOf(asked, name, endsOf) {
93
+ function rankOf(asked, name, endsOf, stem = same) {
87
94
  const wanted = asked.join("");
88
95
  if (!wanted) return -1;
89
96
  if (name.whole === wanted) return 0;
90
97
  if (name.ends.has(wanted.length) && name.whole.startsWith(wanted)) return 1;
91
- if (covers(asked, name.spans)) return 2;
98
+ if (startsAsStem(asked, name, stem)) return 1;
99
+ if (covers(asked, name.spans, stem)) return 2;
92
100
  if (!endsOf) return -1;
93
- return covers(asked, piecesOf(name, endsOf)) ? 3 : -1;
101
+ return covers(asked, piecesOf(name, endsOf, stem), stem) ? 3 : -1;
102
+ }
103
+ function startsAsStem(asked, name, stem) {
104
+ const wanted = asked.join("");
105
+ const whole = stem(wanted);
106
+ const byWord = asked.map(stem).join("");
107
+ let lead = "";
108
+ let leadByWord = "";
109
+ for (const word of name.words) {
110
+ lead += word;
111
+ leadByWord += stem(word);
112
+ if (lead.length > wanted.length + 2) return false;
113
+ if (stem(lead) === whole || leadByWord === byWord) return true;
114
+ }
115
+ return false;
94
116
  }
95
117
  function ask(words, endsOf) {
96
118
  return {
@@ -104,8 +126,8 @@ function ask(words, endsOf) {
104
126
  * words missed. A word of the query may be found by its last part: "Rindergelatine" is a
105
127
  * "Gelatine" with "rinder" missed. Longer words carry more meaning, so letters count, not words.
106
128
  */
107
- function partialOf(asked, name, endsOf) {
108
- const pieces = piecesOf(name, endsOf);
129
+ function partialOf(asked, name, endsOf, stem = same) {
130
+ const pieces = piecesOf(name, endsOf, stem);
109
131
  const best = [{
110
132
  covered: 0,
111
133
  missed: []
@@ -119,7 +141,7 @@ function partialOf(asked, name, endsOf) {
119
141
  }];
120
142
  for (let start = 0; start < end; start++) {
121
143
  const run = asked.runs[end - 1][start];
122
- if (!pieces.has(run)) continue;
144
+ if (!pieces.has(run) && !pieces.has(stem(run))) continue;
123
145
  options.push({
124
146
  covered: best[start].covered + run.length,
125
147
  missed: best[start].missed
@@ -138,16 +160,44 @@ function partialOf(asked, name, endsOf) {
138
160
  const found = best[asked.words.length];
139
161
  return found.covered > 0 ? found : void 0;
140
162
  }
141
- function piecesOf(name, endsOf) {
163
+ function piecesOf(name, endsOf, stem = same) {
142
164
  if (!endsOf) return name.spans;
143
- name.compounds ??= /* @__PURE__ */ new Set([...name.spans, ...name.words.flatMap((word) => endsOf(word))]);
165
+ name.compounds ??= /* @__PURE__ */ new Set([...name.spans, ...name.words.flatMap((word) => endsOf(word).flatMap((head) => [head, stem(head)]))]);
144
166
  return name.compounds;
145
167
  }
146
- function covers(asked, spans) {
168
+ function covers(asked, spans, stem) {
147
169
  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("")));
170
+ for (let end = 1; end <= asked.length; end++) reached[end] = asked.slice(0, end).some((_, start) => {
171
+ if (reached[start] !== true) return false;
172
+ const run = asked.slice(start, end).join("");
173
+ return spans.has(run) || spans.has(stem(run));
174
+ });
149
175
  return reached[asked.length] === true;
150
176
  }
177
+ /**
178
+ * Letters to change, add, drop or swap with a neighbour to turn `a` into `b`; `limit + 1` as soon as
179
+ * it is clear that more than `limit` are needed.
180
+ */
181
+ function distance(a, b, limit) {
182
+ if (Math.abs(a.length - b.length) > limit) return limit + 1;
183
+ let before = [];
184
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
185
+ for (let i = 1; i <= a.length; i++) {
186
+ const current = [i];
187
+ let smallest = i;
188
+ for (let j = 1; j <= b.length; j++) {
189
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
190
+ let value = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
191
+ 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);
192
+ current[j] = value;
193
+ smallest = Math.min(smallest, value);
194
+ }
195
+ if (smallest > limit) return limit + 1;
196
+ before = previous;
197
+ previous = current;
198
+ }
199
+ return Math.min(previous[b.length], limit + 1);
200
+ }
151
201
  // src/variants.ts
152
202
  const ALTERNATIVES = /[^\s,()/]*\/[^\s,()]*/g;
153
203
  /**
@@ -166,53 +216,137 @@ function variants(name) {
166
216
  // src/finder.ts
167
217
  /** Reads every name once; every search reuses it. `names` is code to name. */
168
218
  function createFinder(names, language, options = {}) {
219
+ const stem = language.stem ?? same;
169
220
  const foods = Object.entries(names).map(([code, name]) => ({
170
221
  code,
171
222
  name,
172
- spellings: variants(name).map((variant) => spell(words(variant, language)))
223
+ spellings: variants(name).map((variant) => spell(words(variant, language), stem))
173
224
  }));
174
- const endsOf = language.compounds && compoundsOf(foods, language.compounds);
225
+ const byCode = new Map(foods.map((food) => [food.code, food]));
226
+ const endsOf = language.compounds && compoundsOf(foods, language.compounds, stem);
175
227
  const meant = readMeanings(options.meanings ?? [], language);
176
228
  for (const food of foods) for (const { words: read, order } of meant.get(food.code) ?? []) food.spellings.push({
177
- ...spell(read),
229
+ ...spell(read, stem),
178
230
  meant: order
179
231
  });
180
232
  function search(query, options = {}) {
181
233
  const asked = words(query, language);
182
- const wanted = asked.join("").length;
183
234
  const scope = foods.filter(({ code }) => !options.group || code.startsWith(options.group));
184
- let hits = collect(scope, (spelled) => {
185
- const rank = rankOf(asked, spelled, endsOf);
235
+ let found = find(asked, scope);
236
+ if (found.length === 0) found = mistyped(asked, scope);
237
+ return found.slice(0, options.limit).map(({ code, name, rank, meant, missed }) => ({
238
+ code,
239
+ name,
240
+ match: MATCHES[rank],
241
+ meant: meant !== NOT_MEANT,
242
+ missed
243
+ }));
244
+ }
245
+ function find(asked, scope) {
246
+ const wanted = asked.join("").length;
247
+ const hits = collect(scope, (spelled) => {
248
+ const rank = rankOf(asked, spelled, endsOf, stem);
186
249
  return rank < 0 ? void 0 : {
187
250
  rank,
188
251
  covered: wanted,
189
252
  missed: []
190
253
  };
254
+ }).sort(order);
255
+ const byPreparation = hits.some((hit) => hit.meant !== NOT_MEANT) ? [] : prepared(asked, scope);
256
+ const meant = byPreparation.filter((hit) => hit.meant !== NOT_MEANT);
257
+ if (meant.length > 0) return unique([...meant, ...hits]);
258
+ if (hits.length > 0) return hits;
259
+ if (byPreparation.length > 0) return byPreparation;
260
+ return partials(asked, scope).sort(order);
261
+ }
262
+ function mistyped(asked, scope) {
263
+ const readings = asked.map((word) => vocabulary().has(word) || vocabulary().has(stem(word)) ? [word] : nearest(word));
264
+ if (readings.every((options, index) => options.length === 1 && options[0] === asked[index])) return [];
265
+ 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) => ({
266
+ ...hit,
267
+ rank: FUZZY
268
+ }));
269
+ }
270
+ let known;
271
+ const vocabulary = () => known ??= new Set(foods.flatMap((food) => food.spellings.flatMap((spelled) => spelled.words.filter((word) => /^\p{L}+$/u.test(word)))));
272
+ function nearest(word) {
273
+ if (word.length < 5 || !/^\p{L}+$/u.test(word)) return [];
274
+ const limit = word.length >= 7 ? 2 : 1;
275
+ let best = limit + 1;
276
+ let found = [];
277
+ for (const candidate of vocabulary()) {
278
+ const away = distance(word, candidate, Math.min(best, limit));
279
+ if (away < best) {
280
+ best = away;
281
+ found = [candidate];
282
+ } else if (away === best && away <= limit) found.push(candidate);
283
+ }
284
+ return best <= limit ? found.slice(0, 3) : [];
285
+ }
286
+ function partials(asked, scope) {
287
+ const read = ask(asked, endsOf);
288
+ const food = asked.filter((word) => !isPreparation(word) && word.length >= 4);
289
+ return collect(scope, (spelled) => {
290
+ const partial = partialOf(read, spelled, endsOf, stem);
291
+ if (!partial) return void 0;
292
+ if (food.length > 0 && food.every((word) => partial.missed.includes(word))) return void 0;
293
+ return {
294
+ rank: PARTIAL,
295
+ ...partial
296
+ };
191
297
  });
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
298
+ }
299
+ const order = (a, b) => better(a, b) || a.name.localeCompare(b.name, language.locale) || a.code.localeCompare(b.code);
300
+ const preparations = new Set((language.preparations ?? []).map((word) => stem(words(word, language).join(""))));
301
+ const dish = language.dish && words(language.dish, language)[0];
302
+ const isPreparation = (word) => preparations.has(stem(word)) || preparations.has(stem(word.replace(/(er|es|em)$/, "")));
303
+ function prepared(asked, scope) {
304
+ const preparation = asked.filter(isPreparation);
305
+ const food = asked.filter((word) => !isPreparation(word));
306
+ if (preparation.length === 0 || food.length === 0) return [];
307
+ const wanted = food.join("").length;
308
+ const plain = collect(scope, (spelled) => {
309
+ const rank = rankOf(food, spelled, endsOf, stem);
310
+ return rank < 0 ? void 0 : {
311
+ rank,
312
+ covered: wanted,
313
+ missed: preparation
314
+ };
315
+ }).sort(order);
316
+ if (plain.length === 0) return [];
317
+ const meant = plain.filter((hit) => hit.meant !== NOT_MEANT);
318
+ const seeds = meant.length > 0 ? meant : plain.slice(0, 1);
319
+ const core = (code) => (byCode.get(code)?.spellings[0]?.words ?? []).filter((word) => !isPreparation(word));
320
+ return unique([...seeds.flatMap((seed) => {
321
+ const kernel = core(seed.code);
322
+ return collect(scope, (spelled) => {
323
+ const holds = kernel.every((word) => spelled.words.includes(word));
324
+ if (dish !== void 0 && spelled.words.includes(dish)) return void 0;
325
+ if (!holds || rankOf(preparation, spelled, endsOf, stem) < 0) return void 0;
326
+ return {
327
+ rank: seed.rank,
328
+ covered: asked.join("").length,
329
+ missed: []
199
330
  };
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
- }));
331
+ }).sort(order).map((variant) => ({
332
+ ...variant,
333
+ meant: seed.meant
334
+ }));
335
+ }), ...plain.map((hit) => ({
336
+ ...hit,
337
+ rank: PARTIAL
338
+ }))]);
210
339
  }
211
340
  return { search };
212
341
  }
213
342
  const PARTIAL = MATCHES.indexOf("partial");
343
+ const FUZZY = MATCHES.indexOf("fuzzy");
214
344
  const NOT_MEANT = Infinity;
215
345
  const better = (a, b) => a.rank - b.rank || b.covered - a.covered || a.meant - b.meant || a.length - b.length;
346
+ function unique(hits) {
347
+ const seen = /* @__PURE__ */ new Set();
348
+ return hits.filter(({ code }) => !seen.has(code) && seen.add(code));
349
+ }
216
350
  function collect(foods, read) {
217
351
  return foods.flatMap(({ code, name, spellings }) => {
218
352
  const found = spellings.flatMap((spelled) => {
@@ -231,8 +365,8 @@ function collect(foods, read) {
231
365
  }] : [];
232
366
  });
233
367
  }
234
- function compoundsOf(foods, rules) {
235
- const known = new Set(foods.flatMap((food) => food.spellings.flatMap((spelled) => spelled.words)));
368
+ function compoundsOf(foods, rules, stem) {
369
+ const known = new Set(foods.flatMap((food) => food.spellings.flatMap((spelled) => spelled.words.flatMap((word) => [word, stem(word)]))));
236
370
  for (const ending of rules.endings) known.add(ending);
237
371
  const reading = {
238
372
  known,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thereforejs/food-finder",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
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",