@mdgascar/words 0.8.0 → 0.10.0
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 +29 -16
- package/dist/index.cjs +367 -71
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +146 -16
- package/dist/index.d.ts +146 -16
- package/dist/index.js +363 -71
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -1,36 +1,49 @@
|
|
|
1
1
|
# @mdgascar/words
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Malagasy number words: write numbers in words, ordinals, and read words back into numbers.
|
|
4
|
+
Zero dependencies, ESM + CommonJS + types.
|
|
4
5
|
|
|
5
|
-
Implements spec 0.
|
|
6
|
+
Implements spec 0.9.0.
|
|
6
7
|
|
|
7
8
|
```sh
|
|
8
9
|
npm install @mdgascar/words
|
|
9
10
|
```
|
|
10
11
|
|
|
11
12
|
```ts
|
|
12
|
-
import {
|
|
13
|
+
import { parseWords, spell, spellOrdinal, tryParseWords } from '@mdgascar/words';
|
|
13
14
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
15
|
+
spell(21); // 'iraika amby roapolo'
|
|
16
|
+
spell(2026); // 'enina amby roapolo sy roa arivo'
|
|
17
|
+
spell(3.5); // 'telo faingo dimy'
|
|
18
|
+
|
|
19
|
+
spellOrdinal(1); // 'voalohany'
|
|
20
|
+
spellOrdinal(3); // 'fahatelo'
|
|
21
|
+
|
|
22
|
+
parseWords('roa arivo'); // 2000
|
|
19
23
|
```
|
|
20
24
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
25
|
+
`spell` takes any number from 0 to `Number.MAX_SAFE_INTEGER`, whole or decimal. Bad input
|
|
26
|
+
throws `MdgError` with a code such as `INVALID_TYPE` or `OUT_OF_RANGE`.
|
|
27
|
+
|
|
28
|
+
## Reading words back
|
|
29
|
+
|
|
30
|
+
`parseWords` reads the words `spell` writes, in any case and spacing. It never rounds: a value
|
|
31
|
+
a number cannot hold exactly throws `PRECISION_LOSS`, and `{ as: 'text' }` gives the exact
|
|
32
|
+
digits instead. `safeParseWords` returns the error instead of throwing; `tryParseWords` returns
|
|
33
|
+
`undefined`.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
parseWords('Iraika amby roapolo'); // 21
|
|
37
|
+
tryParseWords('twenty'); // undefined
|
|
38
|
+
```
|
|
24
39
|
|
|
25
40
|
## Traditional system
|
|
26
41
|
|
|
27
|
-
Malagasy also has a name for every power of ten
|
|
28
|
-
`lavitrisa` 10⁹, `alinkisa` 10¹⁰, …), not used in everyday writing. Ask for it with
|
|
29
|
-
`system: 'traditional'`; the default is `'standard'`:
|
|
42
|
+
Malagasy also has a name for every power of ten, not used in everyday writing:
|
|
30
43
|
|
|
31
44
|
```ts
|
|
32
|
-
|
|
33
|
-
|
|
45
|
+
spell(30_000_000); // 'telopolo tapitrisa'
|
|
46
|
+
spell(30_000_000, { system: 'traditional' }); // 'telo safatsiroa'
|
|
34
47
|
```
|
|
35
48
|
|
|
36
49
|
Rules, sources and recorded disagreements: [spec/words](https://github.com/mdgascar/mdg-utils-spec/blob/dev/modules/words/README.md).
|
package/dist/index.cjs
CHANGED
|
@@ -62,58 +62,30 @@ var TRADITIONAL_SCALES = [
|
|
|
62
62
|
{ word: "tsitamboisafaharoa", exponent: 15, countDigits: 1 },
|
|
63
63
|
{ word: "lavitrisafaharoa", exponent: 16, countDigits: 1 },
|
|
64
64
|
{ word: "alinkisafaharoa", exponent: 17, countDigits: 1 },
|
|
65
|
-
{ word: "tsipesimpeseninafaharoa", exponent: 18, countDigits:
|
|
65
|
+
{ word: "tsipesimpeseninafaharoa", exponent: 18, countDigits: 1 }
|
|
66
66
|
];
|
|
67
67
|
var DECIMAL_SEPARATOR = "faingo";
|
|
68
68
|
var JOINER_UNITS_BEFORE_TEN = "ambin'ny";
|
|
69
69
|
var JOINER_BELOW_THOUSAND = "amby";
|
|
70
70
|
var JOINER_BETWEEN_GROUPS = "sy";
|
|
71
71
|
var MIN_VALUE = 0;
|
|
72
|
+
var ORDINAL_FIRST = "voalohany";
|
|
73
|
+
var ORDINAL_PREFIX = "faha";
|
|
74
|
+
var ORDINAL_PREFIX_BEFORE_VOWEL = "fah";
|
|
75
|
+
var VOWELS = ["a", "e", "i", "o", "y"];
|
|
76
|
+
var MAX_TEXT_LENGTH = 100;
|
|
77
|
+
var MAX_WORDS_LENGTH = 4096;
|
|
72
78
|
|
|
73
|
-
// src/
|
|
74
|
-
var SPEC_VERSION = "0.7.0";
|
|
75
|
-
var MdgError = class extends Error {
|
|
76
|
-
/** Always `'MdgError'`. */
|
|
77
|
-
name = "MdgError";
|
|
78
|
-
/** Why the call failed; the same code in every language. */
|
|
79
|
-
code;
|
|
80
|
-
/**
|
|
81
|
-
* Creates an error with a shared spec code.
|
|
82
|
-
*
|
|
83
|
-
* @param code - Shared spec error code.
|
|
84
|
-
* @param message - Human-readable explanation, in English.
|
|
85
|
-
*/
|
|
86
|
-
constructor(code, message) {
|
|
87
|
-
super(message);
|
|
88
|
-
this.code = code;
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Makes `instanceof MdgError` true for errors from any mdg-utils package or build.
|
|
92
|
-
*
|
|
93
|
-
* @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,
|
|
94
|
-
* so the check looks at the error's shape instead of its prototype chain.
|
|
95
|
-
*
|
|
96
|
-
* @param value - Any value, usually a caught error.
|
|
97
|
-
* @returns `true` when `value` is an mdg-utils error.
|
|
98
|
-
*/
|
|
99
|
-
static [Symbol.hasInstance](value) {
|
|
100
|
-
return value instanceof Error && value.name === "MdgError" && "code" in value;
|
|
101
|
-
}
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
// src/number-to-words.ts
|
|
105
|
-
var SCALES_BY_SYSTEM = {
|
|
106
|
-
standard: SCALES,
|
|
107
|
-
traditional: TRADITIONAL_SCALES
|
|
108
|
-
};
|
|
109
|
-
var SYSTEMS = new Set(Object.keys(SCALES_BY_SYSTEM));
|
|
110
|
-
var DEFAULT_SYSTEM = "standard";
|
|
79
|
+
// src/cardinal.ts
|
|
111
80
|
var BASE = 10;
|
|
112
81
|
var HUNDRED = BASE * BASE;
|
|
113
|
-
var
|
|
114
|
-
var ONE = "1";
|
|
82
|
+
var BARE_ONE_EXPONENT = SCALES[0].exponent;
|
|
115
83
|
var LEADING_ZEROS = /^0+/;
|
|
116
|
-
var
|
|
84
|
+
var ONE = "1";
|
|
85
|
+
var JOINERS = {
|
|
86
|
+
number: JOINER_BETWEEN_GROUPS,
|
|
87
|
+
count: JOINER_BELOW_THOUSAND
|
|
88
|
+
};
|
|
117
89
|
function digitAt(value, place) {
|
|
118
90
|
return Math.floor(value / place) % BASE;
|
|
119
91
|
}
|
|
@@ -124,16 +96,24 @@ function belowHundredWords(unitWord, units, tens) {
|
|
|
124
96
|
if (tens === 1 && units > 0) return `${unitWord} ${JOINER_UNITS_BEFORE_TEN} ${TEN_WORDS[1]}`;
|
|
125
97
|
return [unitWord, TEN_WORDS[tens]].filter(isNotEmpty).join(` ${JOINER_BELOW_THOUSAND} `);
|
|
126
98
|
}
|
|
127
|
-
function belowThousandWords(value) {
|
|
99
|
+
function belowThousandWords({ value, role, nextJoiner }) {
|
|
128
100
|
const units = digitAt(value, 1);
|
|
129
101
|
const tens = digitAt(value, BASE);
|
|
130
102
|
const hundreds = digitAt(value, HUNDRED);
|
|
131
|
-
const
|
|
103
|
+
const joiner = role === "count" || hundreds === 1 ? JOINER_BELOW_THOUSAND : JOINER_BETWEEN_GROUPS;
|
|
104
|
+
const afterUnits = tens > 0 || hundreds > 0 ? joiner : nextJoiner;
|
|
105
|
+
const isOneBeforeAmby = units === 1 && (tens > 0 || afterUnits === JOINER_BELOW_THOUSAND);
|
|
132
106
|
const unitWord = isOneBeforeAmby ? UNIT_ONE_IN_COMPOUND : UNIT_WORDS[units];
|
|
133
107
|
const belowHundred = belowHundredWords(unitWord, units, tens);
|
|
134
|
-
const joiner = hundreds === 1 ? JOINER_BELOW_THOUSAND : JOINER_BETWEEN_GROUPS;
|
|
135
108
|
return [belowHundred, HUNDRED_WORDS[hundreds]].filter(isNotEmpty).join(` ${joiner} `);
|
|
136
109
|
}
|
|
110
|
+
var TRADITIONAL_REACH = TRADITIONAL_SCALES.reduce(
|
|
111
|
+
(most, scale) => Math.max(most, scale.exponent + scale.countDigits),
|
|
112
|
+
0
|
|
113
|
+
);
|
|
114
|
+
function scalesFor(digits, system) {
|
|
115
|
+
return system === "traditional" && digits.length <= TRADITIONAL_REACH ? TRADITIONAL_SCALES : SCALES;
|
|
116
|
+
}
|
|
137
117
|
function scaleCount(digits, scale) {
|
|
138
118
|
const end = digits.length - scale.exponent;
|
|
139
119
|
if (end <= 0) return "";
|
|
@@ -143,23 +123,64 @@ function scaleCount(digits, scale) {
|
|
|
143
123
|
function scaleWords(digits, scale, scales) {
|
|
144
124
|
const count = scaleCount(digits, scale);
|
|
145
125
|
if (count === "") return "";
|
|
146
|
-
if (count === ONE && scale.exponent ===
|
|
147
|
-
return `${
|
|
126
|
+
if (count === ONE && scale.exponent === BARE_ONE_EXPONENT) return scale.word;
|
|
127
|
+
return `${numberWords(count, scales, "count")} ${scale.word}`;
|
|
148
128
|
}
|
|
149
|
-
function
|
|
129
|
+
function numberWords(significant, scales, role) {
|
|
130
|
+
const upper = scales.map((scale) => scaleWords(significant, scale, scales)).filter(isNotEmpty);
|
|
131
|
+
const joiner = JOINERS[role];
|
|
132
|
+
const lowest = belowThousandWords({
|
|
133
|
+
value: Number(significant.slice(-3)),
|
|
134
|
+
role,
|
|
135
|
+
nextJoiner: upper.length > 0 ? joiner : ""
|
|
136
|
+
});
|
|
137
|
+
return [lowest, ...upper].filter(isNotEmpty).join(` ${joiner} `);
|
|
138
|
+
}
|
|
139
|
+
function wholeWords(digits, system) {
|
|
150
140
|
const significant = digits.replace(LEADING_ZEROS, "");
|
|
151
141
|
if (significant === "") return ZERO_WORD;
|
|
152
|
-
|
|
153
|
-
belowThousandWords(Number(significant.slice(-3))),
|
|
154
|
-
...scales.map((scale) => scaleWords(significant, scale, scales))
|
|
155
|
-
];
|
|
156
|
-
return groups.filter(isNotEmpty).join(` ${JOINER_BETWEEN_GROUPS} `);
|
|
142
|
+
return numberWords(significant, scalesFor(significant, system), "number");
|
|
157
143
|
}
|
|
158
|
-
function
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
return [...zeros, wholeWords(significant, scales)].join(" ");
|
|
144
|
+
function countWords(count, system) {
|
|
145
|
+
const scales = system === "traditional" ? TRADITIONAL_SCALES : SCALES;
|
|
146
|
+
return numberWords(count.toString(), scales, "count");
|
|
162
147
|
}
|
|
148
|
+
|
|
149
|
+
// src/generated/errors.ts
|
|
150
|
+
var SPEC_VERSION = "0.9.0";
|
|
151
|
+
var MdgError = class extends Error {
|
|
152
|
+
/** Always `'MdgError'`. */
|
|
153
|
+
name = "MdgError";
|
|
154
|
+
/** Why the call failed; the same code in every language. */
|
|
155
|
+
code;
|
|
156
|
+
/**
|
|
157
|
+
* Creates an error with a shared spec code.
|
|
158
|
+
*
|
|
159
|
+
* @param code - Shared spec error code.
|
|
160
|
+
* @param message - Human-readable explanation, in English.
|
|
161
|
+
*/
|
|
162
|
+
constructor(code, message) {
|
|
163
|
+
super(message);
|
|
164
|
+
this.code = code;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Makes `instanceof MdgError` true for errors from any mdg-utils package or build.
|
|
168
|
+
*
|
|
169
|
+
* @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,
|
|
170
|
+
* so the check looks at the error's shape instead of its prototype chain.
|
|
171
|
+
*
|
|
172
|
+
* @param value - Any value, usually a caught error.
|
|
173
|
+
* @returns `true` when `value` is an mdg-utils error.
|
|
174
|
+
*/
|
|
175
|
+
static [Symbol.hasInstance](value) {
|
|
176
|
+
return value instanceof Error && value.name === "MdgError" && "code" in value;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
// src/decimal-text.ts
|
|
181
|
+
var TRAILING_ZEROS = /0+$/;
|
|
182
|
+
var DECIMAL_TEXT = /^([0-9]+)(?:\.([0-9]+))?$/;
|
|
183
|
+
var NEGATIVE_EXPONENT = /^(\d)(?:\.(\d+))?e-(\d+)$/;
|
|
163
184
|
function plainDecimal(value) {
|
|
164
185
|
const text = String(value);
|
|
165
186
|
const match = NEGATIVE_EXPONENT.exec(text);
|
|
@@ -167,37 +188,312 @@ function plainDecimal(value) {
|
|
|
167
188
|
const [, lead = "", rest = "", exponent = ""] = match;
|
|
168
189
|
return `0.${"0".repeat(Number(exponent) - 1)}${lead}${rest}`;
|
|
169
190
|
}
|
|
170
|
-
function
|
|
191
|
+
function decimalTextParts(text, caller) {
|
|
192
|
+
const match = text.length <= MAX_TEXT_LENGTH ? DECIMAL_TEXT.exec(text) : null;
|
|
193
|
+
if (match === null) {
|
|
194
|
+
throw new MdgError(
|
|
195
|
+
"INVALID_FORMAT",
|
|
196
|
+
`${caller} reads digits with an optional .decimals, at most ${String(MAX_TEXT_LENGTH)} characters.`
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
const [, whole = "", decimals = ""] = match;
|
|
200
|
+
const significantDecimals = decimals.replace(TRAILING_ZEROS, "");
|
|
201
|
+
return [whole, significantDecimals === "" ? void 0 : significantDecimals];
|
|
202
|
+
}
|
|
203
|
+
function assertSupportedNumber(value, caller) {
|
|
171
204
|
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
172
|
-
throw new MdgError("INVALID_TYPE",
|
|
205
|
+
throw new MdgError("INVALID_TYPE", `${caller} expects a finite number or decimal text.`);
|
|
173
206
|
}
|
|
174
207
|
if (value < MIN_VALUE || value > Number.MAX_SAFE_INTEGER) {
|
|
175
208
|
throw new MdgError(
|
|
176
209
|
"OUT_OF_RANGE",
|
|
177
|
-
|
|
210
|
+
`${caller} supports ${String(MIN_VALUE)} to ${String(Number.MAX_SAFE_INTEGER)}.`
|
|
178
211
|
);
|
|
179
212
|
}
|
|
180
213
|
}
|
|
181
|
-
function
|
|
214
|
+
function decimalParts(value, caller) {
|
|
215
|
+
if (typeof value === "string") return decimalTextParts(value, caller);
|
|
216
|
+
assertSupportedNumber(value, caller);
|
|
217
|
+
const [whole = "", decimals] = plainDecimal(value).split(".");
|
|
218
|
+
return [whole, decimals];
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/system.ts
|
|
222
|
+
var SYSTEMS = ["standard", "traditional"];
|
|
223
|
+
var DEFAULT_SYSTEM = "standard";
|
|
224
|
+
function systemOf(options) {
|
|
182
225
|
if (typeof options !== "object" || options === null) {
|
|
183
|
-
throw new MdgError("INVALID_TYPE", "
|
|
226
|
+
throw new MdgError("INVALID_TYPE", "spell options must be an object.");
|
|
184
227
|
}
|
|
185
228
|
const { system = DEFAULT_SYSTEM } = options;
|
|
186
|
-
if (!SYSTEMS.
|
|
229
|
+
if (!SYSTEMS.includes(system)) {
|
|
187
230
|
throw new MdgError("INVALID_TYPE", "system is standard or traditional.");
|
|
188
231
|
}
|
|
189
|
-
return
|
|
232
|
+
return system;
|
|
190
233
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
234
|
+
|
|
235
|
+
// src/spell.ts
|
|
236
|
+
var LEADING_ZEROS2 = /^0+/;
|
|
237
|
+
function decimalWords(digits, system) {
|
|
238
|
+
const significant = digits.replace(LEADING_ZEROS2, "");
|
|
239
|
+
const zeros = Array.from({ length: digits.length - significant.length }, () => ZERO_WORD);
|
|
240
|
+
return [...zeros, wholeWords(significant, system)].join(" ");
|
|
241
|
+
}
|
|
242
|
+
function partsWords(whole, decimals, system) {
|
|
243
|
+
const wholePart = wholeWords(whole, system);
|
|
244
|
+
if (decimals === void 0) return wholePart;
|
|
245
|
+
return `${wholePart} ${DECIMAL_SEPARATOR} ${decimalWords(decimals, system)}`;
|
|
246
|
+
}
|
|
247
|
+
function spell(value, options = {}) {
|
|
248
|
+
const [whole, decimals] = decimalParts(value, "spell");
|
|
249
|
+
return partsWords(whole, decimals, systemOf(options));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// src/ordinal.ts
|
|
253
|
+
var STARTS_WITH_VOWEL = new Set(VOWELS);
|
|
254
|
+
var LEADING_ZEROS3 = /^0+/;
|
|
255
|
+
var ONE2 = "1";
|
|
256
|
+
var POINT = ".";
|
|
257
|
+
function ordinalDigits(value) {
|
|
258
|
+
if (typeof value === "string" && value.includes(POINT)) {
|
|
259
|
+
throw new MdgError("INVALID_FORMAT", "spellOrdinal reads whole digits, with no point.");
|
|
260
|
+
}
|
|
261
|
+
const [whole, decimals] = decimalParts(value, "spellOrdinal");
|
|
262
|
+
if (decimals !== void 0) {
|
|
263
|
+
throw new MdgError("INVALID_TYPE", "spellOrdinal expects a whole number.");
|
|
264
|
+
}
|
|
265
|
+
const significant = whole.replace(LEADING_ZEROS3, "");
|
|
266
|
+
if (significant === "") {
|
|
267
|
+
throw new MdgError("OUT_OF_RANGE", "Ordinals start at 1 (voalohany).");
|
|
268
|
+
}
|
|
269
|
+
return significant;
|
|
270
|
+
}
|
|
271
|
+
function spellOrdinal(value, options = {}) {
|
|
272
|
+
const digits = ordinalDigits(value);
|
|
273
|
+
const cardinal = wholeWords(digits, systemOf(options));
|
|
274
|
+
if (digits === ONE2) return ORDINAL_FIRST;
|
|
275
|
+
const prefix = STARTS_WITH_VOWEL.has(cardinal.charAt(0)) ? ORDINAL_PREFIX_BEFORE_VOWEL : ORDINAL_PREFIX;
|
|
276
|
+
return `${prefix}${cardinal}`;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// src/read-words.ts
|
|
280
|
+
var BASE2 = 10;
|
|
281
|
+
var TOKENS_PER_STEP = 2;
|
|
282
|
+
var TEN = BigInt(BASE2);
|
|
283
|
+
var HUNDRED2 = BASE2 * BASE2;
|
|
284
|
+
var MAX_READINGS = 8;
|
|
285
|
+
var PHRASE_JOINERS = /* @__PURE__ */ new Set([
|
|
286
|
+
JOINER_BELOW_THOUSAND,
|
|
287
|
+
JOINER_UNITS_BEFORE_TEN
|
|
288
|
+
]);
|
|
289
|
+
function wordValues(words, step) {
|
|
290
|
+
return words.flatMap((word, digit) => word === "" ? [] : [[word, digit * step]]);
|
|
291
|
+
}
|
|
292
|
+
var PHRASE_VALUES = new Map([
|
|
293
|
+
...wordValues(UNIT_WORDS, 1),
|
|
294
|
+
[UNIT_ONE_IN_COMPOUND, 1],
|
|
295
|
+
...wordValues(TEN_WORDS, BASE2),
|
|
296
|
+
...wordValues(HUNDRED_WORDS, HUNDRED2)
|
|
297
|
+
]);
|
|
298
|
+
var MAX_PHRASE_TOKENS = 5;
|
|
299
|
+
function groupWord(exponent, countDigits) {
|
|
300
|
+
const factor = TEN ** BigInt(exponent);
|
|
301
|
+
const maxLeftTokens = countWords(factor - BigInt(1), "standard").split(" ").length;
|
|
302
|
+
return { factor, hasPhraseCount: countDigits !== null, maxLeftTokens };
|
|
303
|
+
}
|
|
304
|
+
var GROUP_WORDS = new Map(
|
|
305
|
+
[...TRADITIONAL_SCALES, ...SCALES].map((scale) => [
|
|
306
|
+
scale.word,
|
|
307
|
+
groupWord(scale.exponent, scale.countDigits)
|
|
308
|
+
])
|
|
309
|
+
);
|
|
310
|
+
function readPhrase(tokens) {
|
|
311
|
+
let total = 0;
|
|
312
|
+
for (const [index, token] of tokens.entries()) {
|
|
313
|
+
const isJoinerPlace = index % TOKENS_PER_STEP === 1;
|
|
314
|
+
if (isJoinerPlace !== PHRASE_JOINERS.has(token)) return void 0;
|
|
315
|
+
if (!isJoinerPlace) total += PHRASE_VALUES.get(token) ?? Number.NaN;
|
|
316
|
+
}
|
|
317
|
+
return tokens.length % TOKENS_PER_STEP === 1 && !Number.isNaN(total) ? BigInt(total) : void 0;
|
|
318
|
+
}
|
|
319
|
+
function sums(lefts, rights, factor) {
|
|
320
|
+
return [...lefts].flatMap((left) => [...rights].map((right) => left + right * factor));
|
|
321
|
+
}
|
|
322
|
+
function groupSums(lefts, counts, factor) {
|
|
323
|
+
return sums(
|
|
324
|
+
[...lefts].filter((left) => left < factor),
|
|
325
|
+
counts,
|
|
326
|
+
factor
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
function limited(values) {
|
|
330
|
+
return [...new Set(values)].slice(0, MAX_READINGS);
|
|
331
|
+
}
|
|
332
|
+
var CountReader = class {
|
|
333
|
+
spans = /* @__PURE__ */ new Map();
|
|
334
|
+
tokens;
|
|
335
|
+
constructor(tokens) {
|
|
336
|
+
this.tokens = tokens;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Counts written exactly as spell writes a count before a group word.
|
|
340
|
+
*
|
|
341
|
+
* @param start - First token of the count.
|
|
342
|
+
* @param end - Token after the count.
|
|
343
|
+
* @returns The counts those tokens spell.
|
|
344
|
+
*/
|
|
345
|
+
counts(start, end) {
|
|
346
|
+
const text = this.tokens.slice(start, end).join(" ");
|
|
347
|
+
return this.values(start, end).filter(
|
|
348
|
+
(count) => SYSTEMS.some((system) => countWords(count, system) === text)
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
// Every value of tokens[start, end): a phrase, or parts joined by amby ending in a group.
|
|
352
|
+
values(start, end) {
|
|
353
|
+
const key = `${String(start)}:${String(end)}`;
|
|
354
|
+
const known = this.spans.get(key);
|
|
355
|
+
if (known !== void 0) return known;
|
|
356
|
+
const phrase = readPhrase(this.tokens.slice(start, end));
|
|
357
|
+
const found = limited([...phrase === void 0 ? [] : [phrase], ...this.grouped(start, end)]);
|
|
358
|
+
this.spans.set(key, found);
|
|
359
|
+
return found;
|
|
360
|
+
}
|
|
361
|
+
// "dimy arivo amby roa alina": whatever comes before an amby, plus a count of the last group.
|
|
362
|
+
grouped(start, end) {
|
|
363
|
+
const group = GROUP_WORDS.get(String(this.tokens[end - 1]));
|
|
364
|
+
if (group === void 0) return [];
|
|
365
|
+
const first = group.hasPhraseCount ? Math.max(start, end - 1 - MAX_PHRASE_TOKENS) : start;
|
|
366
|
+
const last = Math.min(end - 1, start + group.maxLeftTokens + 1);
|
|
367
|
+
const found = [];
|
|
368
|
+
for (let split = first; split <= last; split += 1) {
|
|
369
|
+
if (split > start && this.tokens[split - 1] !== JOINER_BELOW_THOUSAND) continue;
|
|
370
|
+
const lefts = split === start ? [BigInt(0)] : this.values(start, split - 1);
|
|
371
|
+
const counts = split === end - 1 ? [BigInt(1)] : this.counts(split, end - 1);
|
|
372
|
+
found.push(...groupSums(lefts, counts, group.factor));
|
|
373
|
+
}
|
|
374
|
+
return found;
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
function splitOn(tokens, separator) {
|
|
378
|
+
const parts = [[]];
|
|
379
|
+
for (const token of tokens) {
|
|
380
|
+
if (token === separator) parts.push([]);
|
|
381
|
+
else parts[parts.length - 1]?.push(token);
|
|
382
|
+
}
|
|
383
|
+
return parts;
|
|
384
|
+
}
|
|
385
|
+
function groupValues(tokens) {
|
|
386
|
+
const factor = GROUP_WORDS.get(String(tokens[tokens.length - 1]))?.factor;
|
|
387
|
+
if (factor === void 0) {
|
|
388
|
+
const phrase = readPhrase(tokens);
|
|
389
|
+
return phrase === void 0 ? [] : [phrase];
|
|
390
|
+
}
|
|
391
|
+
const counts = tokens.length === 1 ? [BigInt(1)] : new CountReader(tokens).counts(0, tokens.length - 1);
|
|
392
|
+
return counts.map((count) => count * factor);
|
|
393
|
+
}
|
|
394
|
+
function wholeValues(tokens) {
|
|
395
|
+
if (tokens.length === 1 && tokens[0] === ZERO_WORD) return [BigInt(0)];
|
|
396
|
+
return splitOn(tokens, JOINER_BETWEEN_GROUPS).reduce(
|
|
397
|
+
(totals, group) => limited(sums(totals, groupValues(group), BigInt(1))),
|
|
398
|
+
[BigInt(0)]
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
function decimalValues(tokens) {
|
|
402
|
+
const zeros = tokens.findIndex((token) => token !== ZERO_WORD);
|
|
403
|
+
if (zeros < 0) return [];
|
|
404
|
+
const prefix = "0".repeat(zeros);
|
|
405
|
+
return wholeValues(tokens.slice(zeros)).map((value) => `${prefix}${value.toString()}`);
|
|
406
|
+
}
|
|
407
|
+
function readWords(words) {
|
|
408
|
+
const [wholeTokens = [], decimalTokens, ...extra] = splitOn(words.split(" "), DECIMAL_SEPARATOR);
|
|
409
|
+
if (extra.length > 0) return { wholes: [], decimals: void 0 };
|
|
410
|
+
return {
|
|
411
|
+
wholes: wholeValues(wholeTokens),
|
|
412
|
+
decimals: decimalTokens === void 0 ? void 0 : decimalValues(decimalTokens)
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// src/parse.ts
|
|
417
|
+
var RESULT_KINDS = /* @__PURE__ */ new Set(["number", "text"]);
|
|
418
|
+
var OPTION_KEYS = /* @__PURE__ */ new Set(["as"]);
|
|
419
|
+
var APOSTROPHES = /[‘’ʼ`´]/g;
|
|
420
|
+
var SPACES = /\s+/gu;
|
|
421
|
+
var SPLIT_AMBINNY = /\bambin' ny\b|\bamby ny\b/g;
|
|
422
|
+
var AMBINNY = "ambin'ny";
|
|
423
|
+
var TRAILING_ZEROS2 = /0+$/;
|
|
424
|
+
function failure(code, message) {
|
|
425
|
+
return { success: false, error: new MdgError(code, message) };
|
|
426
|
+
}
|
|
427
|
+
function resultKind(options) {
|
|
428
|
+
if (typeof options !== "object" || options === null) return void 0;
|
|
429
|
+
if (Object.keys(options).some((key) => !OPTION_KEYS.has(key))) return void 0;
|
|
430
|
+
const { as = "number" } = options;
|
|
431
|
+
return RESULT_KINDS.has(as) ? as : void 0;
|
|
432
|
+
}
|
|
433
|
+
function normalise(text) {
|
|
434
|
+
return text.toLowerCase().replace(APOSTROPHES, "'").replace(SPACES, " ").trim().replace(SPLIT_AMBINNY, AMBINNY);
|
|
435
|
+
}
|
|
436
|
+
function spelledReadings(words) {
|
|
437
|
+
const { wholes, decimals } = readWords(words);
|
|
438
|
+
const texts = wholes.flatMap(
|
|
439
|
+
(whole) => (decimals ?? [""]).map((digits) => {
|
|
440
|
+
const significant = digits.replace(TRAILING_ZEROS2, "");
|
|
441
|
+
return significant === "" ? whole.toString() : `${whole.toString()}.${significant}`;
|
|
442
|
+
})
|
|
443
|
+
);
|
|
444
|
+
return [...new Set(texts)].filter((text) => {
|
|
445
|
+
const [whole = "", decimal] = text.split(".");
|
|
446
|
+
return SYSTEMS.some((system) => partsWords(whole, decimal, system) === words);
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
function readExact(words) {
|
|
450
|
+
const readings = spelledReadings(words);
|
|
451
|
+
const [only, ...others] = readings;
|
|
452
|
+
if (only === void 0) {
|
|
453
|
+
return failure("INVALID_FORMAT", "Expected Malagasy number words, as spell writes them.");
|
|
454
|
+
}
|
|
455
|
+
if (others.length > 0) {
|
|
456
|
+
return failure("AMBIGUOUS", `These words read as ${readings.join(" and as ")}.`);
|
|
457
|
+
}
|
|
458
|
+
return { success: true, data: only };
|
|
459
|
+
}
|
|
460
|
+
function asNumber(text) {
|
|
461
|
+
const value = Number(text);
|
|
462
|
+
if (value <= Number.MAX_SAFE_INTEGER && plainDecimal(value) === text) {
|
|
463
|
+
return { success: true, data: value };
|
|
464
|
+
}
|
|
465
|
+
return failure(
|
|
466
|
+
"PRECISION_LOSS",
|
|
467
|
+
`${text} does not fit a number exactly; pass { as: 'text' } for the exact digits.`
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
function safeParseWords(text, options = {}) {
|
|
471
|
+
if (typeof text !== "string") return failure("INVALID_TYPE", "Expected the words as text.");
|
|
472
|
+
const kind = resultKind(options);
|
|
473
|
+
if (kind === void 0) return failure("INVALID_TYPE", "as is 'number' or 'text'.");
|
|
474
|
+
if (text.length > MAX_WORDS_LENGTH) {
|
|
475
|
+
return failure("INVALID_FORMAT", `Words are at most ${String(MAX_WORDS_LENGTH)} characters.`);
|
|
476
|
+
}
|
|
477
|
+
const exact = readExact(normalise(text));
|
|
478
|
+
if (!exact.success || kind === "text") return exact;
|
|
479
|
+
return asNumber(exact.data);
|
|
480
|
+
}
|
|
481
|
+
function parseWords(text, options = {}) {
|
|
482
|
+
const result = safeParseWords(text, options);
|
|
483
|
+
if (!result.success) throw result.error;
|
|
484
|
+
return result.data;
|
|
485
|
+
}
|
|
486
|
+
function tryParseWords(text, options = {}) {
|
|
487
|
+
const result = safeParseWords(text, options);
|
|
488
|
+
return result.success ? result.data : void 0;
|
|
197
489
|
}
|
|
198
490
|
|
|
199
491
|
exports.MdgError = MdgError;
|
|
200
492
|
exports.SPEC_VERSION = SPEC_VERSION;
|
|
201
|
-
exports.
|
|
493
|
+
exports.parseWords = parseWords;
|
|
494
|
+
exports.safeParseWords = safeParseWords;
|
|
495
|
+
exports.spell = spell;
|
|
496
|
+
exports.spellOrdinal = spellOrdinal;
|
|
497
|
+
exports.tryParseWords = tryParseWords;
|
|
202
498
|
//# sourceMappingURL=index.cjs.map
|
|
203
499
|
//# sourceMappingURL=index.cjs.map
|