Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1292 lines (1134 loc) · 45.1 KB
/
Copy pathindex.js
File metadata and controls
1292 lines (1134 loc) · 45.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
/## /"" /""
| ## | "" |__/
/####### /## /## /######/#### | ####### /###### /###### /""""""" /"""""" /"""""" /"" /""""""" /""""""
| ##__ ##| ## | ##| ##_ ##_ ##| ##__ ## /##__ ## /##__ ## /""_____/|_ ""_/ /""__ ""| ""| ""__ "" /""__ ""
| ## \ ##| ## | ##| ## \ ## \ ##| ## \ ##| ########| ## \__/| """""" | "" | "" \__/| ""| "" \ ""| "" \ ""
| ## | ##| ## | ##| ## | ## | ##| ## | ##| ##_____/| ## \____ "" | "" /""| "" | ""| "" | ""| "" | ""
| ## | ##| ######/| ## | ## | ##| #######/| #######| ## /"""""""/ | """"/| "" | ""| "" | ""| """""""
|__/ |__/ \______/ |__/ |__/ |__/|_______/ \_______/|__/ |_______/ \___/ |__/ |__/|__/ |__/ \____ ""
/"" \ ""
| """"""/
\______/
*/
/**
* numberstring - Convert numbers to their word representation
* Supports 22 languages including English, Spanish, French, German, Danish, Chinese, Hindi, Russian, Portuguese, Japanese, Korean, Arabic, Italian, Dutch, Turkish, Polish, Swedish, Indonesian, Thai, Norwegian, Finnish, and Icelandic
* @module numberstring
*/
// Import language functions
import { english, spanish, french, german, danish, chinese, hindi, russian, portuguese, japanese, korean, arabic, italian, dutch, turkish, polish, swedish, indonesian, thai, norwegian, finnish, icelandic, LANGUAGES } from './languages/index.js';
import { fancy, FANCY_STYLE_NAMES, egyptian, babylonian, greek, clock } from './numerals.js';
// Re-export language functions and alternative numeral systems
export { spanish, french, german, danish, chinese, hindi, russian, portuguese, japanese, korean, arabic, italian, dutch, turkish, polish, swedish, indonesian, thai, norwegian, finnish, icelandic };
export { fancy, FANCY_STYLE_NAMES, egyptian, babylonian, greek, clock };
export { CAP_STYLES };
// ============================================================================
// CONSTANTS
// ============================================================================
const ONES = Object.freeze(['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']);
const TENS = Object.freeze(['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']);
const TEENS = Object.freeze(['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']);
const ILLIONS = Object.freeze(['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion']);
// Ordinal words
const ORDINAL_ONES = Object.freeze(['', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth']);
const ORDINAL_TEENS = Object.freeze(['tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth']);
const ORDINAL_TENS = Object.freeze(['', '', 'twentieth', 'thirtieth', 'fortieth', 'fiftieth', 'sixtieth', 'seventieth', 'eightieth', 'ninetieth']);
// Currency configurations
const CURRENCIES = Object.freeze({
'$': { code: 'USD', main: 'dollar', sub: 'cent', subPer: 100 },
'USD': { code: 'USD', main: 'dollar', sub: 'cent', subPer: 100 },
'€': { code: 'EUR', main: 'euro', sub: 'cent', subPer: 100 },
'EUR': { code: 'EUR', main: 'euro', sub: 'cent', subPer: 100 },
'£': { code: 'GBP', main: 'pound', sub: 'penny', subPlural: 'pence', subPer: 100 },
'GBP': { code: 'GBP', main: 'pound', sub: 'penny', subPlural: 'pence', subPer: 100 },
'¥': { code: 'JPY', main: 'yen', sub: null, subPer: 1 },
'JPY': { code: 'JPY', main: 'yen', sub: null, subPer: 1 },
'₹': { code: 'INR', main: 'rupee', sub: 'paisa', subPlural: 'paise', subPer: 100 },
'INR': { code: 'INR', main: 'rupee', sub: 'paisa', subPlural: 'paise', subPer: 100 },
'元': { code: 'CNY', main: 'yuan', sub: 'fen', subPer: 100 },
'CNY': { code: 'CNY', main: 'yuan', sub: 'fen', subPer: 100 }
});
// Roman numeral mappings
const ROMAN_VALUES = Object.freeze([
[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
[100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],
[10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']
]);
// Word to number mappings (for parse function)
const WORD_VALUES = Object.freeze({
'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5,
'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10,
'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15,
'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19,
'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50,
'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90
});
const SCALE_VALUES = Object.freeze({
'hundred': 100,
'thousand': 1000,
'million': 1000000,
'billion': 1000000000,
'trillion': 1000000000000,
'quadrillion': 1000000000000000n,
'quintillion': 1000000000000000000n,
'sextillion': 1000000000000000000000n,
'septillion': 1000000000000000000000000n,
'octillion': 1000000000000000000000000000n,
'nonillion': 1000000000000000000000000000000n,
'decillion': 1000000000000000000000000000000000n
});
/** Maximum supported value (10^36 - 1, up to decillions) */
const MAX_VALUE = 10n ** 36n - 1n;
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
const group = (n) => {
if (typeof n !== 'number' && typeof n !== 'bigint') return false;
if (typeof n === 'number' && !Number.isFinite(n)) return false;
return Math.ceil((n < 0 ? -n : n).toString().length / 3) - 1;
};
const power = (g) => 10n ** BigInt(g * 3);
const segment = (n, g) => n % power(g + 1);
const hundment = (n, g) => Number(segment(n, g) / power(g));
const tenment = (n, g) => hundment(n, g) % 100;
const hundred = (n) => {
if (n < 100 || n >= 1000) return '';
return `${ONES[Math.floor(n / 100)]} hundred `;
};
const ten = (n) => {
if (n === 0) return '';
if (n < 10) return `${ONES[n]} `;
if (n < 20) return `${TEENS[n - 10]} `;
const onesDigit = n % 10;
if (onesDigit) return `${TENS[Math.floor(n / 10)]}-${ONES[onesDigit]} `;
return `${TENS[Math.floor(n / 10)]} `;
};
/** Casing styles accepted by the `cap` option */
const CAP_STYLES = Object.freeze(['title', 'upper', 'lower', 'sentence', 'camel', 'pascal', 'snake', 'kebab', 'hyphen', 'constant', 'screaming', 'dot']);
const capFirst = (w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();
/**
* Apply a casing style. Word-joining styles split on spaces and hyphens:
* 'one hundred twenty-three' → camel 'oneHundredTwentyThree', snake
* 'one_hundred_twenty_three', kebab 'one-hundred-twenty-three'.
*/
const cap = (str, style) => {
const words = () => str.split(/[\s-]+/).filter(Boolean);
switch (style) {
case 'title':
return str.replace(/\w([^-\s]*)/g, (txt) =>
txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase()
);
case 'upper':
return str.toUpperCase();
case 'lower':
return str.toLowerCase();
case 'sentence':
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
case 'camel':
return words().map((w, i) => (i === 0 ? w.toLowerCase() : capFirst(w))).join('');
case 'pascal':
return words().map(capFirst).join('');
case 'snake':
return words().map((w) => w.toLowerCase()).join('_');
case 'kebab':
case 'hyphen':
return words().map((w) => w.toLowerCase()).join('-');
case 'constant':
case 'screaming':
return words().map((w) => w.toUpperCase()).join('_');
case 'dot':
return words().map((w) => w.toLowerCase()).join('.');
default:
return str;
}
};
const punc = (str, p) => {
if (p == null) return str;
if (/[!?.]/.test(p)) return str + p;
return str;
};
const comma = (n) => {
if (typeof n === 'bigint') {
return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
if (typeof n === 'number') {
if (!Number.isFinite(n)) return false;
const [intPart, fracPart] = n.toString().split('.');
const grouped = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return fracPart === undefined ? grouped : `${grouped}.${fracPart}`;
}
if (typeof n === 'string' && /^-?\d+(\.\d+)?$/.test(n.trim())) {
const [intPart, fracPart] = n.trim().split('.');
const grouped = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return fracPart === undefined ? grouped : `${grouped}.${fracPart}`;
}
return false;
};
// ============================================================================
// MAIN CONVERSION FUNCTION
// ============================================================================
/**
* Convert a non-negative integer (number or BigInt) to English words.
* Internal: the public `string()` normalizes input and delegates here.
* @param {number|bigint} n - The number to convert (0 to 10^36-1)
* @param {Object} [opt] - Options object
* @param {boolean} [opt.and] - British "and" after hundreds / before a final group under 100
* @returns {string|false} The word representation or false if invalid
*/
const cardinal = (n, opt) => {
let num;
if (typeof n === 'bigint') {
if (n < 0n || n > MAX_VALUE) return false;
num = n;
} else if (typeof n === 'number') {
if (isNaN(n) || n < 0 || !Number.isInteger(n)) return false;
if (n > Number.MAX_SAFE_INTEGER) return false;
num = BigInt(n);
} else {
return false;
}
let s = '';
const useAnd = opt?.and === true;
if (num === 0n) {
s = 'zero';
} else {
for (let i = group(num); i >= 0; i--) {
const h = hundment(num, i);
if (h === 0) continue;
const t = tenment(num, i);
s += hundred(h);
// British style: "one hundred and one", "one thousand and one"
if (useAnd && t > 0 && (h >= 100 || (i === 0 && s))) s += 'and ';
s += ten(t);
s += `${ILLIONS[i]} `;
}
}
s = s.trim();
if (opt) {
if (opt.cap) s = cap(s, opt.cap);
if (opt.punc !== undefined) s = punc(s, opt.punc);
}
return s;
};
/**
* Convert a number to its word representation.
*
* Forgiving by design: accepts integers, negatives, decimals, numeric strings,
* and BigInt, and honors `opt.lang` for any of the 22 supported languages.
* Invalid input returns `false`.
*
* @param {number|bigint|string} n - The number to convert
* @param {Object} [opt] - Options object
* @param {string} [opt.cap] - Casing: 'title', 'upper', 'lower', 'sentence', 'camel', 'pascal', 'snake', 'kebab', 'constant', 'dot'
* @param {string} [opt.punc] - Punctuation: '!', '?', or '.'
* @param {string} [opt.lang] - Language code (default 'en')
* @param {string} [opt.point] - Word for the decimal point (default 'point')
* @param {boolean} [opt.and] - British style: 'one hundred and twenty-three'
* @returns {string|false} The word representation or false if invalid
*
* @example
* numberstring(42) // 'forty-two'
* numberstring(123, { and: true }) // 'one hundred and twenty-three'
* numberstring(-5) // 'negative five'
* numberstring(3.14) // 'three point one four'
* numberstring('1000') // 'one thousand'
* numberstring(42, { lang: 'es' }) // 'cuarenta y dos'
*/
const string = (n, opt) => {
let value = n;
// Delegates apply `cap` themselves; `punc` is applied once in finish()
const inner = opt ? { ...opt, punc: undefined } : opt;
const lang = typeof opt?.lang === 'string' ? opt.lang.toLowerCase() : undefined;
const foreign = Boolean(lang && LANGUAGES[lang] && LANGUAGES[lang] !== 'english');
if (typeof value === 'string') {
const str = value.trim();
if (!/^-?\d+(\.\d+)?$/.test(str)) return false;
// Other languages only cover non-negative integers; don't fall back to English
if (str.includes('.')) return foreign ? false : finish(decimal(str, inner), opt);
const digits = str.replace('-', '');
value = digits.length <= 15 ? Number(str) : BigInt(str);
}
if (typeof value === 'number') {
if (!Number.isFinite(value)) return false;
if (!Number.isInteger(value)) return foreign ? false : finish(decimal(value, inner), opt);
// 1e21 is an integer too; widen to BigInt rather than rejecting it
if (Math.abs(value) > Number.MAX_SAFE_INTEGER) value = BigInt(value);
}
if (typeof value === 'number') {
if (value < 0) return foreign ? false : finish(negative(value, inner), opt);
} else if (typeof value === 'bigint') {
if (value < 0n) return foreign ? false : finish(negative(value, inner), opt);
} else {
return false;
}
if (foreign) return finish(toWords(value, inner), opt);
return cardinal(value, opt);
};
/** Apply `punc` to a delegated result (helpers already apply `cap`). */
const finish = (result, opt) => {
if (result === false) return false;
if (opt?.punc !== undefined) return punc(result, opt.punc);
return result;
};
// ============================================================================
// ORDINAL FUNCTION
// ============================================================================
const ordinal = (n, opt) => {
let num;
if (typeof n === 'bigint') {
if (n <= 0n || n > MAX_VALUE) return false;
num = Number(n);
if (n > BigInt(Number.MAX_SAFE_INTEGER)) return false;
} else if (typeof n === 'number') {
if (isNaN(n) || n <= 0 || !Number.isInteger(n)) return false;
if (n > Number.MAX_SAFE_INTEGER) return false;
num = n;
} else {
return false;
}
let s;
if (num <= 9) {
s = ORDINAL_ONES[num];
} else if (num <= 19) {
s = ORDINAL_TEENS[num - 10];
} else if (num <= 99) {
const onesDigit = num % 10;
const tensDigit = Math.floor(num / 10);
if (onesDigit === 0) {
s = ORDINAL_TENS[tensDigit];
} else {
s = `${TENS[tensDigit]}-${ORDINAL_ONES[onesDigit]}`;
}
} else {
const base = cardinal(num, { and: opt?.and });
if (!base) return false;
const parts = base.split(' ');
const lastPart = parts[parts.length - 1];
const hyphenParts = lastPart.split('-');
const lastWord = hyphenParts[hyphenParts.length - 1];
const ordinalMap = {
'one': 'first', 'two': 'second', 'three': 'third', 'four': 'fourth',
'five': 'fifth', 'six': 'sixth', 'seven': 'seventh', 'eight': 'eighth',
'nine': 'ninth', 'ten': 'tenth', 'eleven': 'eleventh', 'twelve': 'twelfth',
'thirteen': 'thirteenth', 'fourteen': 'fourteenth', 'fifteen': 'fifteenth',
'sixteen': 'sixteenth', 'seventeen': 'seventeenth', 'eighteen': 'eighteenth',
'nineteen': 'nineteenth', 'twenty': 'twentieth', 'thirty': 'thirtieth',
'forty': 'fortieth', 'fifty': 'fiftieth', 'sixty': 'sixtieth',
'seventy': 'seventieth', 'eighty': 'eightieth', 'ninety': 'ninetieth',
'hundred': 'hundredth', 'thousand': 'thousandth', 'million': 'millionth',
'billion': 'billionth', 'trillion': 'trillionth', 'quadrillion': 'quadrillionth',
'quintillion': 'quintillionth'
};
const ordinalWord = ordinalMap[lastWord] || (lastWord + 'th');
if (hyphenParts.length > 1) {
hyphenParts[hyphenParts.length - 1] = ordinalWord;
parts[parts.length - 1] = hyphenParts.join('-');
} else {
parts[parts.length - 1] = ordinalWord;
}
s = parts.join(' ');
}
if (opt?.cap) s = cap(s, opt.cap);
return s;
};
// ============================================================================
// DECIMAL FUNCTION
// ============================================================================
const decimal = (n, opt) => {
let numStr;
if (typeof n === 'number') {
if (!Number.isFinite(n)) return false;
numStr = n.toString();
if (numStr.includes('e')) {
if (!Number.isInteger(n)) return false;
numStr = BigInt(n).toString();
}
} else if (typeof n === 'string') {
numStr = n.trim();
if (!/^-?\d+\.?\d*$/.test(numStr) && !/^-?\d*\.?\d+$/.test(numStr)) {
return false;
}
} else {
return false;
}
const isNegative = numStr.startsWith('-');
if (isNegative) numStr = numStr.slice(1);
const pointWord = opt?.point || 'point';
const [intPart, decPart] = numStr.split('.');
const intDigits = intPart || '0';
const intNum = intDigits.length <= 15 ? parseInt(intDigits, 10) : BigInt(intDigits);
const intWords = cardinal(intNum, { and: opt?.and });
if (intWords === false) return false;
let result = isNegative ? 'negative ' : '';
result += intWords;
if (decPart) {
result += ` ${pointWord}`;
for (const digit of decPart) {
const digitWord = digit === '0' ? 'zero' : ONES[parseInt(digit, 10)];
result += ` ${digitWord}`;
}
}
if (opt?.cap) result = cap(result, opt.cap);
return result;
};
// ============================================================================
// CURRENCY FUNCTION
// ============================================================================
const currency = (amount, opt) => {
let numStr = String(amount).trim();
let currencyKey = opt?.currency;
const symbolMatch = numStr.match(/^([$€£¥₹元])/);
if (symbolMatch) {
currencyKey = currencyKey || symbolMatch[1];
numStr = numStr.slice(1).trim();
}
const codeMatch = numStr.match(/\s*(USD|EUR|GBP|JPY|INR|CNY)$/i);
if (codeMatch) {
currencyKey = currencyKey || codeMatch[1].toUpperCase();
numStr = numStr.slice(0, -codeMatch[0].length).trim();
}
if (!currencyKey) return false;
const currConfig = CURRENCIES[currencyKey];
if (!currConfig) return false;
const num = parseFloat(numStr);
if (isNaN(num) || num < 0) return false;
const mainUnits = Math.floor(num);
const subUnits = Math.round((num - mainUnits) * currConfig.subPer);
let result = '';
if (mainUnits > 0 || (mainUnits === 0 && subUnits === 0)) {
const mainWords = string(mainUnits);
if (mainWords === false) return false;
const noPlural = ['yen', 'yuan'];
const mainName = mainUnits === 1 || noPlural.includes(currConfig.main)
? currConfig.main
: currConfig.main + 's';
result = `${mainWords} ${mainName}`;
}
if (subUnits > 0 && currConfig.sub) {
const subWords = string(subUnits);
if (subWords === false) return false;
let subName;
if (subUnits === 1) {
subName = currConfig.sub;
} else {
subName = currConfig.subPlural || currConfig.sub + 's';
}
if (result) {
result += ` and ${subWords} ${subName}`;
} else {
result = `${subWords} ${subName}`;
}
}
if (opt?.cap) result = cap(result, opt.cap);
return result;
};
// ============================================================================
// ROMAN NUMERAL FUNCTION
// ============================================================================
/** Classic Roman numerals for 1-3999 */
const romanBase = (n) => {
let result = '';
let remaining = n;
for (const [value, numeral] of ROMAN_VALUES) {
while (remaining >= value) {
result += numeral;
remaining -= value;
}
}
return result;
};
/** Combining marks for vinculum notation: one bar = x1000, two bars = x1000000 */
const ROMAN_BARS = Object.freeze(['', '\u0305', '\u033F']);
/** Maximum value expressible with a double vinculum (3,999,999,999) */
const ROMAN_MAX = 3999999999;
/**
* Convert to Roman numerals. Classic numerals cover 1-3999; above that,
* vinculum notation places a bar over a group to multiply it by 1000, so
* 4000 is I̅V̅ and 8675309 is V̿I̿I̿I̿D̅C̅L̅X̅X̅V̅CCCIX.
* @param {number} n - Integer from 1 to 3,999,999,999
* @param {Object} [opt] - Options object
* @param {boolean} [opt.lower] - Return lowercase numerals
* @returns {string|false} The Roman numeral or false if out of range
*/
const roman = (n, opt) => {
if (typeof n !== 'number' || isNaN(n) || !Number.isInteger(n)) return false;
if (n < 1 || n > ROMAN_MAX) return false;
let result = '';
let remaining = n;
let level = 0;
while (remaining > 0) {
// The topmost group keeps the classic form up to 3999; lower groups are 0-999
const groupValue = remaining < 4000 ? remaining : remaining % 1000;
const bar = ROMAN_BARS[level];
const letters = romanBase(groupValue);
const barred = bar ? [...letters].map((ch) => ch + bar).join('') : letters;
result = barred + result;
remaining = (remaining - groupValue) / 1000;
level++;
}
return opt?.lower ? result.toLowerCase() : result;
};
// ============================================================================
// PARSE FUNCTION (Reverse: words to number)
// ============================================================================
const parse = (str) => {
if (typeof str !== 'string') return false;
const normalized = str.toLowerCase().trim();
if (normalized === 'zero') return 0;
const words = normalized.split(/[\s-]+/).filter(w => w);
if (words.length === 0) return false;
let useBigInt = false;
for (const word of words) {
const scale = SCALE_VALUES[word];
if (typeof scale === 'bigint') {
useBigInt = true;
break;
}
}
let result = useBigInt ? 0n : 0;
let current = useBigInt ? 0n : 0;
let lastSimple = null;
for (const word of words) {
if (Object.hasOwn(WORD_VALUES, word)) {
const val = WORD_VALUES[word];
// Only "tens + ones" (twenty two) may follow a simple word directly;
// "nineteen eighty" is a year, not a cardinal
const tensThenOnes = lastSimple >= 20 && lastSimple % 10 === 0 && val >= 1 && val <= 9;
if (lastSimple !== null && !tensThenOnes) return false;
lastSimple = val;
if (useBigInt) {
current += BigInt(val);
} else {
current += val;
}
} else if (word === 'hundred') {
lastSimple = null;
if (useBigInt) {
current *= 100n;
} else {
current *= 100;
}
} else if (Object.hasOwn(SCALE_VALUES, word)) {
lastSimple = null;
const scale = SCALE_VALUES[word];
if (useBigInt) {
const bigScale = typeof scale === 'bigint' ? scale : BigInt(scale);
current *= bigScale;
result += current;
current = 0n;
} else {
current *= scale;
result += current;
current = 0;
}
} else if (word === 'and') {
continue;
} else {
return false;
}
}
result += current;
return result;
};
// ============================================================================
// NTH (numeric ordinal suffix)
// ============================================================================
/**
* Append the English ordinal suffix to a number: 1st, 2nd, 3rd, 4th, 11th, 112th.
* @param {number|bigint|string} n - Integer (negatives keep their sign)
* @returns {string|false}
*
* @example
* nth(1) // '1st'
* nth(22) // '22nd'
* nth(113) // '113th'
*/
const nth = (n) => {
let value;
if (typeof n === 'bigint') value = n;
else if (typeof n === 'number' && Number.isInteger(n) && Math.abs(n) <= Number.MAX_SAFE_INTEGER) value = BigInt(n);
else if (typeof n === 'string' && /^-?\d+$/.test(n.trim())) value = BigInt(n.trim());
else return false;
const abs = value < 0n ? -value : value;
const mod100 = Number(abs % 100n);
const mod10 = Number(abs % 10n);
let suffix = 'th';
if (mod100 < 11 || mod100 > 13) {
if (mod10 === 1) suffix = 'st';
else if (mod10 === 2) suffix = 'nd';
else if (mod10 === 3) suffix = 'rd';
}
return `${value}${suffix}`;
};
// ============================================================================
// COMPACT (1.5K, 2.3M)
// ============================================================================
/** Short suffixes aligned with ILLIONS: thousand, million, billion, ... */
const COMPACT_SUFFIXES = Object.freeze(['', 'K', 'M', 'B', 'T', 'Qa', 'Qi', 'Sx', 'Sp', 'Oc', 'No', 'Dc']);
/**
* Compact notation: 1500 → '1.5K', 2300000 → '2.3M'.
* @param {number|bigint|string} n - The number
* @param {Object} [opt] - Options object
* @param {number} [opt.digits=1] - Maximum decimal places
* @param {boolean} [opt.long] - Spell the scale: '1.5 thousand'
* @returns {string|false}
*
* @example
* compact(1500) // '1.5K'
* compact(2300000000) // '2.3B'
* compact(999950) // '1M'
* compact(1500000, { long: true }) // '1.5 million'
*/
const compact = (n, opt) => {
let str;
if (typeof n === 'bigint') str = n.toString();
else if (typeof n === 'number') {
if (!Number.isFinite(n)) return false;
str = Number.isInteger(n) ? BigInt(n).toString() : n.toString();
if (str.includes('e')) return false;
} else if (typeof n === 'string' && /^-?\d+(\.\d+)?$/.test(n.trim())) str = n.trim();
else return false;
const negative = str.startsWith('-');
if (negative) str = str.slice(1);
const [rawInt, fracPart = ''] = str.split('.');
// Leading zeros carry no magnitude: '0001000' is 1000
const intPart = rawInt.replace(/^0+(?=\d)/, '');
const digits = Number.isFinite(opt?.digits) ? Math.max(0, Math.min(Math.trunc(opt.digits), 6)) : 1;
if (intPart.length < 4) {
const small = Number(`${intPart}.${fracPart || '0'}`);
const rounded = Number(small.toFixed(digits));
// 999.99 rounds up to 1000, which belongs in the next scale
if (rounded < 1000) return `${negative ? '-' : ''}${rounded}`;
return `${negative ? '-' : ''}1${opt?.long ? ` ${ILLIONS[1]}` : COMPACT_SUFFIXES[1]}`;
}
let g = Math.floor((intPart.length - 1) / 3);
if (g >= COMPACT_SUFFIXES.length) return false;
// Value / 10^(3g) as a float; precision loss is irrelevant at <= 6 decimals
const scaled = Number(`${intPart.slice(0, intPart.length - 3 * g)}.${intPart.slice(intPart.length - 3 * g)}${fracPart}`);
let value = Number(scaled.toFixed(digits));
// Rounding can carry into the next scale; at the last scale keep 1000Dc
if (value >= 1000 && g + 1 < COMPACT_SUFFIXES.length) {
g++;
value = Number((value / 1000).toFixed(digits));
}
const scale = opt?.long ? ` ${ILLIONS[g]}` : COMPACT_SUFFIXES[g];
return `${negative ? '-' : ''}${value}${scale}`;
};
// ============================================================================
// NATO / ICAO PHONETIC NUMERALS
// ============================================================================
/** ICAO radiotelephony pronunciations for the digits */
const NATO_DIGITS = Object.freeze(['zero', 'wun', 'too', 'tree', 'fower', 'fife', 'six', 'seven', 'ait', 'niner']);
/**
* NATO / ICAO radiotelephony numerals. Digits are read one at a time
* (1984 → 'wun niner ait fower'); per ICAO, whole hundreds and thousands
* are read with 'hundred' and 'tousand' (2500 → 'too tousand fife hundred').
* A decimal point is 'decimal', a negative sign 'minus'.
* @param {number|bigint|string} n - The number
* @param {Object} [opt] - Options object
* @param {boolean} [opt.digits] - Always read digit by digit, even round numbers
* @param {string} [opt.cap] - Capitalization: 'title', 'upper', or 'lower'
* @returns {string|false}
*
* @example
* nato(1984) // 'wun niner ait fower'
* nato(2500) // 'too tousand fife hundred'
* nato(3.14) // 'tree decimal wun fower'
*/
const nato = (n, opt) => {
let str;
if (typeof n === 'bigint') str = n.toString();
else if (typeof n === 'number') {
if (!Number.isFinite(n)) return false;
str = Number.isInteger(n) ? BigInt(n).toString() : n.toString();
if (str.includes('e')) return false;
} else if (typeof n === 'string' && /^-?\d+(\.\d+)?$/.test(n.trim())) str = n.trim();
else return false;
const words = [];
if (str.startsWith('-')) {
words.push('minus');
str = str.slice(1);
}
const [intPart, fracPart] = str.split('.');
const spell = (digits) => [...digits].map((d) => NATO_DIGITS[Number(d)]);
// Round hundreds / thousands: "fife hundred", "wun tousand", "too fife tousand"
const roundMatch = !opt?.digits && !fracPart && intPart.match(/^(\d{1,2})(\d?)(00)$/);
if (roundMatch && !intPart.startsWith('0') && intPart.length >= 3 && intPart.length <= 5) {
const thousands = intPart.slice(0, -3);
const hundredsDigit = intPart.slice(-3, -2);
if (thousands) words.push(...spell(thousands), 'tousand');
if (hundredsDigit !== '0') words.push(NATO_DIGITS[Number(hundredsDigit)], 'hundred');
} else {
words.push(...spell(intPart));
if (fracPart) words.push('decimal', ...spell(fracPart));
}
let result = words.join(' ');
if (opt?.cap) result = cap(result, opt.cap);
return result;
};
// ============================================================================
// SCIENTIFIC NOTATION
// ============================================================================
/** Expand a float's exponent form ('1.5e-7') into a plain decimal string */
const expandExponent = (str) => {
const negative = str.startsWith('-');
const [m, e] = (negative ? str.slice(1) : str).split('e');
const exp = Number(e);
const mDigits = m.replace('.', '');
const point = m.split('.')[0].length + exp;
let out;
if (point <= 0) out = `0.${'0'.repeat(-point)}${mDigits}`;
else if (point >= mDigits.length) out = `${mDigits}${'0'.repeat(point - mDigits.length)}`;
else out = `${mDigits.slice(0, point)}.${mDigits.slice(point)}`;
return (negative ? '-' : '') + out;
};
/** Normalize number | bigint | numeric string to a plain decimal string, or null */
const toPlainDecimal = (n) => {
if (typeof n === 'bigint') return n.toString();
if (typeof n === 'number') {
if (!Number.isFinite(n)) return null;
const str = n.toString();
return str.includes('e') ? expandExponent(str) : str;
}
if (typeof n === 'string' && /^-?\d+(\.\d+)?$/.test(n.trim())) return n.trim();
return null;
};
/**
* Scientific notation with an exact decimal mantissa (no float drift).
* @param {number|bigint|string} n - The number
* @param {Object} [opt] - Options object
* @param {number} [opt.digits=12] - Maximum significant digits (rounds half up)
* @param {string} [opt.format='unicode'] - 'unicode' (1.984 × 10³), 'caret' (1.984 × 10^3),
* 'e' (1.984e3), or 'words' (one point nine eight four times ten to the third)
* @param {string} [opt.cap] - Capitalization for the words format
* @returns {string|false}
*
* @example
* scientific(1984) // '1.984 × 10³'
* scientific(0.00042) // '4.2 × 10⁻⁴'
* scientific(1984, { format: 'e' }) // '1.984e3'
* scientific(1984, { format: 'words' }) // 'one point nine eight four times ten to the third'
*/
const scientific = (n, opt) => {
let str = toPlainDecimal(n);
if (str === null) return false;
const negative = str.startsWith('-');
if (negative) str = str.slice(1);
const [rawInt, fracPart = ''] = str.split('.');
const intPart = rawInt.replace(/^0+/, '');
const all = intPart + fracPart;
const firstNonZero = all.search(/[1-9]/);
let exponent = 0;
let sig = '0';
if (firstNonZero !== -1) {
exponent = intPart ? intPart.length - 1 : -(firstNonZero + 1);
sig = all.slice(firstNonZero).replace(/0+$/, '') || '0';
}
const maxDigits = Number.isFinite(opt?.digits) ? Math.max(1, Math.min(Math.trunc(opt.digits), 36)) : 12;
if (sig.length > maxDigits) {
const rounded = BigInt(sig.slice(0, maxDigits)) + (Number(sig[maxDigits]) >= 5 ? 1n : 0n);
let roundedStr = rounded.toString();
if (roundedStr.length > maxDigits) {
// 999 → 1000 carries into the exponent
exponent++;
roundedStr = roundedStr.slice(0, -1);
}
sig = roundedStr.replace(/0+$/, '') || '0';
}
const mantissa = sig.length > 1 ? `${sig[0]}.${sig.slice(1)}` : sig;
const sign = negative ? '-' : '';
const format = opt?.format || 'unicode';
if (format === 'e') return `${sign}${mantissa}e${exponent}`;
if (format === 'caret') return `${sign}${mantissa} × 10^${exponent}`;
if (format === 'words') {
const mantissaWords = decimal(`${sign}${mantissa}`);
if (mantissaWords === false) return false;
let result = mantissaWords;
if (exponent !== 0) {
const power = exponent < 0 ? `negative ${ordinal(-exponent)}` : ordinal(exponent);
result += ` times ten to the ${power}`;
}
return opt?.cap ? cap(result, opt.cap) : result;
}
if (format !== 'unicode') return false;
return `${sign}${mantissa} × 10${fancy(exponent, 'superscript')}`;
};
// ============================================================================
// RADIX (binary, octal, hex)
// ============================================================================
const RADIX_PREFIXES = Object.freeze({ 2: '0b', 8: '0o', 16: '0x' });
/**
* Integer in another base, 2 to 36.
* @param {number|bigint|string} n - Integer
* @param {number} [base=2] - Radix, 2 to 36
* @param {Object} [opt] - Options object
* @param {boolean} [opt.prefix] - Add 0b / 0o / 0x for bases 2, 8, 16
* @param {boolean} [opt.upper] - Uppercase letter digits
* @param {number} [opt.pad] - Left-pad with zeros to this many digits
* @returns {string|false}
*
* @example
* radix(42) // '101010'
* radix(42, 16) // '2a'
* radix(255, 16, { prefix: true, upper: true }) // '0xFF'
*/
const radix = (n, base = 2, opt) => {
if (!Number.isInteger(base) || base < 2 || base > 36) return false;
let value;
if (typeof n === 'bigint') value = n;
else if (typeof n === 'number' && Number.isInteger(n) && Math.abs(n) <= Number.MAX_SAFE_INTEGER) value = BigInt(n);
else if (typeof n === 'string' && /^-?\d+$/.test(n.trim())) value = BigInt(n.trim());
else return false;
const negative = value < 0n;
let digits = (negative ? -value : value).toString(base);
if (opt?.upper) digits = digits.toUpperCase();
if (opt?.pad) digits = digits.padStart(opt.pad, '0');
const prefix = opt?.prefix ? (RADIX_PREFIXES[base] || '') : '';
return `${negative ? '-' : ''}${prefix}${digits}`;
};
/** Binary: 42 → '101010' */
const binary = (n, opt) => radix(n, 2, opt);
/** Octal: 42 → '52' */
const octal = (n, opt) => radix(n, 8, opt);
/** Hexadecimal: 42 → '2a' */
const hex = (n, opt) => radix(n, 16, opt);
// ============================================================================
// BYTES
// ============================================================================
const BYTE_UNITS = Object.freeze({
decimal: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
binary: ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
decimalWords: ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte', 'exabyte', 'zettabyte', 'yottabyte'],
binaryWords: ['byte', 'kibibyte', 'mebibyte', 'gibibyte', 'tebibyte', 'pebibyte', 'exbibyte', 'zebibyte', 'yobibyte']
});
const BIT_UNITS = Object.freeze({
decimal: ['b', 'kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb'],
binary: ['b', 'Kib', 'Mib', 'Gib', 'Tib', 'Pib', 'Eib', 'Zib', 'Yib'],
decimalWords: ['bit', 'kilobit', 'megabit', 'gigabit', 'terabit', 'petabit', 'exabit', 'zettabit', 'yottabit'],
binaryWords: ['bit', 'kibibit', 'mebibit', 'gibibit', 'tebibit', 'pebibit', 'exbibit', 'zebibit', 'yobibit']
});
/** Shared engine for bytes() and bits(): all rounding in BigInt, so precision holds at any size */
const dataSize = (n, opt, table) => {
let value;
if (typeof n === 'bigint') value = n;
else if (typeof n === 'number' && Number.isInteger(n) && n <= Number.MAX_SAFE_INTEGER) value = BigInt(n);
else if (typeof n === 'string' && /^\d+$/.test(n.trim())) value = BigInt(n.trim());
else return false;
if (value < 0n) return false;
const step = opt?.binary ? 1024n : 1000n;
const units = opt?.binary ? table.binary : table.decimal;
const words = opt?.binary ? table.binaryWords : table.decimalWords;
// Clamp to a finite integer 0-6 so BigInt() cannot throw on 1.5, NaN, or Infinity
const digits = Number.isFinite(opt?.digits) ? Math.max(0, Math.min(Math.trunc(opt.digits), 6)) : 1;
const precision = 10n ** BigInt(digits);
let unit = 0;
let scale = 1n;
while (unit < units.length - 1 && value >= scale * step) {
scale *= step;
unit++;
}
// amount in units of 10^-digits, rounded half up
let fixed = (value * precision * 2n + scale) / (scale * 2n);
if (fixed >= step * precision && unit < units.length - 1) {
unit++;
scale *= step;
fixed = (value * precision * 2n + scale) / (scale * 2n);
}
const whole = (fixed / precision).toString();
const frac = digits ? (fixed % precision).toString().padStart(digits, '0').replace(/0+$/, '') : '';
const amountStr = frac ? `${whole}.${frac}` : whole;
if (opt?.long) {
const amountWords = frac ? decimal(amountStr) : cardinal(BigInt(whole));
if (amountWords === false) return false;
const noun = amountStr === '1' ? words[unit] : `${words[unit]}s`;
return `${amountWords} ${noun}`;
}
return `${amountStr} ${units[unit]}`;
};
/**
* Human-readable byte sizes.
* @param {number|bigint|string} n - Non-negative integer count of bytes
* @param {Object} [opt] - Options object
* @param {boolean} [opt.binary] - Use 1024 steps and KiB/MiB units
* @param {number} [opt.digits=1] - Maximum decimal places
* @param {boolean} [opt.long] - Spell it out: 'one point five kilobytes'
* @returns {string|false}
*
* @example
* bytes(1536) // '1.5 KB'
* bytes(1536, { binary: true }) // '1.5 KiB'
* bytes(1536, { long: true }) // 'one point five kilobytes'
*/
const bytes = (n, opt) => dataSize(n, opt, BYTE_UNITS);
/**
* Human-readable bit counts (bandwidth style: kb, Mb, Gb).
* @param {number|bigint|string} n - Non-negative integer count of bits
* @param {Object} [opt] - Same options as bytes()
* @returns {string|false}
*
* @example
* bits(1500000) // '1.5 Mb'
* bits(1536, { binary: true }) // '1.5 Kib'
* bits(1500000, { long: true }) // 'one point five megabits'