numeric-quantity 3.1.0 → 3.2.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 +173 -17
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/numeric-quantity.cjs.development.d.ts +225 -0
- package/dist/cjs/numeric-quantity.cjs.development.js +101 -16
- package/dist/cjs/numeric-quantity.cjs.development.js.map +1 -1
- package/dist/cjs/numeric-quantity.cjs.production.d.ts +225 -0
- package/dist/cjs/numeric-quantity.cjs.production.js +1 -1
- package/dist/cjs/numeric-quantity.cjs.production.js.map +1 -1
- package/dist/numeric-quantity.d.mts +225 -0
- package/dist/numeric-quantity.iife.umd.min.js +1 -1
- package/dist/numeric-quantity.iife.umd.min.js.map +1 -1
- package/dist/numeric-quantity.legacy-esm.d.ts +225 -0
- package/dist/numeric-quantity.legacy-esm.js +98 -17
- package/dist/numeric-quantity.legacy-esm.js.map +1 -1
- package/dist/numeric-quantity.mjs +101 -17
- package/dist/numeric-quantity.mjs.map +1 -1
- package/dist/numeric-quantity.production.d.mts +225 -0
- package/dist/numeric-quantity.production.mjs +1 -1
- package/dist/numeric-quantity.production.mjs.map +1 -1
- package/package.json +5 -6
- package/dist/types/constants.d.ts +0 -87
- package/dist/types/dev.d.ts +0 -1
- package/dist/types/index.d.ts +0 -4
- package/dist/types/numericQuantity.d.ts +0 -12
- package/dist/types/parseRomanNumerals.d.ts +0 -8
- package/dist/types/types.d.ts +0 -49
- package/dist/types-esm/constants.d.mts +0 -87
- package/dist/types-esm/dev.d.mts +0 -1
- package/dist/types-esm/index.d.mts +0 -4
- package/dist/types-esm/numericQuantity.d.mts +0 -12
- package/dist/types-esm/parseRomanNumerals.d.mts +0 -8
- package/dist/types-esm/types.d.mts +0 -49
|
@@ -136,7 +136,7 @@ const vulgarFractionToAsciiMap = {
|
|
|
136
136
|
* | # | Description | Example(s) |
|
|
137
137
|
* | --- | ------------------------------------------------ | ------------------------------------------------------------------- |
|
|
138
138
|
* | `0` | entire string | `"2 1/3"` from `"2 1/3"` |
|
|
139
|
-
* | `1` |
|
|
139
|
+
* | `1` | sign (`-` or `+`) | `"-"` from `"-2 1/3"` |
|
|
140
140
|
* | `2` | whole number or numerator | `"2"` from `"2 1/3"`; `"1"` from `"1/3"` |
|
|
141
141
|
* | `3` | entire fraction, decimal portion, or denominator | `" 1/3"` from `"2 1/3"`; `".33"` from `"2.33"`; `"/3"` from `"1/3"` |
|
|
142
142
|
*
|
|
@@ -152,11 +152,12 @@ const vulgarFractionToAsciiMap = {
|
|
|
152
152
|
* numericRegex.exec("2 / 3") // [ "2 / 3", "2", "/ 3", null ]
|
|
153
153
|
* ```
|
|
154
154
|
*/
|
|
155
|
-
const numericRegex = /^(
|
|
155
|
+
const numericRegex = /^(?=[-+]?\s*\.\d|[-+]?\s*\d)([-+])?\s*((?:\d(?:[,_]\d|\d)*)*)(([eE][+-]?\d(?:[,_]\d|\d)*)?|\.\d(?:[,_]\d|\d)*([eE][+-]?\d(?:[,_]\d|\d)*)?|(\s+\d(?:[,_]\d|\d)*\s*)?\s*\/\s*\d(?:[,_]\d|\d)*)?$/;
|
|
156
156
|
/**
|
|
157
157
|
* Same as {@link numericRegex}, but allows (and ignores) trailing invalid characters.
|
|
158
|
+
* Capture group 7 contains the trailing invalid portion.
|
|
158
159
|
*/
|
|
159
|
-
const numericRegexWithTrailingInvalid = /^(
|
|
160
|
+
const numericRegexWithTrailingInvalid = /^(?=[-+]?\s*\.\d|[-+]?\s*\d)([-+])?\s*((?:\d(?:[,_]\d|\d)*)*)(([eE][+-]?\d(?:[,_]\d|\d)*)?|\.\d(?:[,_]\d|\d)*([eE][+-]?\d(?:[,_]\d|\d)*)?|(\s+\d(?:[,_]\d|\d)*\s*)?\s*\/\s*\d(?:[,_]\d|\d)*)?(\s*[^.\d/].*)?/;
|
|
160
161
|
/**
|
|
161
162
|
* Captures any Unicode vulgar fractions.
|
|
162
163
|
*/
|
|
@@ -269,7 +270,10 @@ const defaultOptions = {
|
|
|
269
270
|
allowTrailingInvalid: false,
|
|
270
271
|
romanNumerals: false,
|
|
271
272
|
bigIntOnOverflow: false,
|
|
272
|
-
decimalSeparator: "."
|
|
273
|
+
decimalSeparator: ".",
|
|
274
|
+
allowCurrency: false,
|
|
275
|
+
percentage: false,
|
|
276
|
+
verbose: false
|
|
273
277
|
};
|
|
274
278
|
|
|
275
279
|
//#endregion
|
|
@@ -359,18 +363,65 @@ function _objectSpread2(e) {
|
|
|
359
363
|
//#endregion
|
|
360
364
|
//#region src/numericQuantity.ts
|
|
361
365
|
const spaceThenSlashRegex = /^\s*\//;
|
|
366
|
+
const currencyPrefixRegex = /* @__PURE__ */ new RegExp("^([-+]?)\\s*(\\p{Sc}+)\\s*", "u");
|
|
367
|
+
const currencySuffixRegex = /* @__PURE__ */ new RegExp("\\s*(\\p{Sc}+)$", "u");
|
|
368
|
+
const percentageSuffixRegex = /%$/;
|
|
362
369
|
function numericQuantity(quantity, options = defaultOptions) {
|
|
363
|
-
if (typeof quantity === "number" || typeof quantity === "bigint") return quantity;
|
|
364
|
-
let finalResult = NaN;
|
|
365
|
-
const quantityAsString = normalizeDigits(`${quantity}`.replace(vulgarFractionsRegex, (_m, vf) => ` ${vulgarFractionToAsciiMap[vf]}`).replace("⁄", "/").trim());
|
|
366
|
-
if (quantityAsString.length === 0) return NaN;
|
|
367
370
|
const opts = _objectSpread2(_objectSpread2({}, defaultOptions), options);
|
|
371
|
+
const originalInput = typeof quantity === "string" ? quantity : `${quantity}`;
|
|
372
|
+
let currencyPrefix;
|
|
373
|
+
let currencySuffix;
|
|
374
|
+
let percentageSuffix;
|
|
375
|
+
let trailingInvalid;
|
|
376
|
+
let parsedSign;
|
|
377
|
+
let parsedWhole;
|
|
378
|
+
let parsedNumerator;
|
|
379
|
+
let parsedDenominator;
|
|
380
|
+
const buildVerboseResult = (value) => {
|
|
381
|
+
const result = {
|
|
382
|
+
value,
|
|
383
|
+
input: originalInput
|
|
384
|
+
};
|
|
385
|
+
if (currencyPrefix) result.currencyPrefix = currencyPrefix;
|
|
386
|
+
if (currencySuffix) result.currencySuffix = currencySuffix;
|
|
387
|
+
if (percentageSuffix) result.percentageSuffix = percentageSuffix;
|
|
388
|
+
if (trailingInvalid) result.trailingInvalid = trailingInvalid;
|
|
389
|
+
if (parsedSign) result.sign = parsedSign;
|
|
390
|
+
if (parsedWhole !== void 0) result.whole = parsedWhole;
|
|
391
|
+
if (parsedNumerator !== void 0) result.numerator = parsedNumerator;
|
|
392
|
+
if (parsedDenominator !== void 0) result.denominator = parsedDenominator;
|
|
393
|
+
return result;
|
|
394
|
+
};
|
|
395
|
+
const returnValue = (value) => opts.verbose ? buildVerboseResult(value) : value;
|
|
396
|
+
if (typeof quantity === "number" || typeof quantity === "bigint") return returnValue(quantity);
|
|
397
|
+
let finalResult = NaN;
|
|
398
|
+
let workingString = `${quantity}`;
|
|
399
|
+
if (opts.allowCurrency) {
|
|
400
|
+
const prefixMatch = currencyPrefixRegex.exec(workingString);
|
|
401
|
+
if (prefixMatch && prefixMatch[2]) {
|
|
402
|
+
currencyPrefix = prefixMatch[2];
|
|
403
|
+
workingString = (prefixMatch[1] || "") + workingString.slice(prefixMatch[0].length);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (opts.allowCurrency) {
|
|
407
|
+
const suffixMatch = currencySuffixRegex.exec(workingString);
|
|
408
|
+
if (suffixMatch) {
|
|
409
|
+
currencySuffix = suffixMatch[1];
|
|
410
|
+
workingString = workingString.slice(0, -suffixMatch[0].length);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (opts.percentage && percentageSuffixRegex.test(workingString)) {
|
|
414
|
+
percentageSuffix = true;
|
|
415
|
+
workingString = workingString.slice(0, -1);
|
|
416
|
+
}
|
|
417
|
+
const quantityAsString = normalizeDigits(workingString.replace(vulgarFractionsRegex, (_m, vf) => ` ${vulgarFractionToAsciiMap[vf]}`).replace("⁄", "/").trim());
|
|
418
|
+
if (quantityAsString.length === 0) return returnValue(NaN);
|
|
368
419
|
let normalizedString = quantityAsString;
|
|
369
420
|
if (opts.decimalSeparator === ",") {
|
|
370
421
|
const commaCount = (quantityAsString.match(/,/g) || []).length;
|
|
371
422
|
if (commaCount === 1) normalizedString = quantityAsString.replaceAll(".", "_").replace(",", ".");
|
|
372
423
|
else if (commaCount > 1) {
|
|
373
|
-
if (!opts.allowTrailingInvalid) return NaN;
|
|
424
|
+
if (!opts.allowTrailingInvalid) return returnValue(NaN);
|
|
374
425
|
const firstCommaIndex = quantityAsString.indexOf(",");
|
|
375
426
|
const secondCommaIndex = quantityAsString.indexOf(",", firstCommaIndex + 1);
|
|
376
427
|
const beforeSecondComma = quantityAsString.substring(0, secondCommaIndex).replaceAll(".", "_").replace(",", ".");
|
|
@@ -378,20 +429,30 @@ function numericQuantity(quantity, options = defaultOptions) {
|
|
|
378
429
|
normalizedString = opts.allowTrailingInvalid ? beforeSecondComma + "&" + afterSecondComma : beforeSecondComma;
|
|
379
430
|
} else normalizedString = quantityAsString.replaceAll(".", "_");
|
|
380
431
|
}
|
|
381
|
-
const regexResult =
|
|
382
|
-
if (!regexResult) return opts.romanNumerals ? parseRomanNumerals(quantityAsString) : NaN;
|
|
383
|
-
const
|
|
432
|
+
const regexResult = numericRegexWithTrailingInvalid.exec(normalizedString);
|
|
433
|
+
if (!regexResult) return returnValue(opts.romanNumerals ? parseRomanNumerals(quantityAsString) : NaN);
|
|
434
|
+
const rawTrailing = (regexResult[7] || normalizedString.slice(regexResult[0].length)).trim();
|
|
435
|
+
if (rawTrailing) {
|
|
436
|
+
trailingInvalid = rawTrailing;
|
|
437
|
+
if (!opts.allowTrailingInvalid) return returnValue(NaN);
|
|
438
|
+
}
|
|
439
|
+
const [, sign, ng1temp, ng2temp] = regexResult;
|
|
440
|
+
if (sign === "-" || sign === "+") parsedSign = sign;
|
|
384
441
|
const numberGroup1 = ng1temp.replaceAll(",", "").replaceAll("_", "");
|
|
385
442
|
const numberGroup2 = ng2temp === null || ng2temp === void 0 ? void 0 : ng2temp.replaceAll(",", "").replaceAll("_", "");
|
|
386
443
|
if (!numberGroup1 && numberGroup2 && numberGroup2.startsWith(".")) finalResult = 0;
|
|
387
444
|
else {
|
|
388
445
|
if (opts.bigIntOnOverflow) {
|
|
389
|
-
const asBigInt =
|
|
390
|
-
if (asBigInt > BigInt(Number.MAX_SAFE_INTEGER) || asBigInt < BigInt(Number.MIN_SAFE_INTEGER)) return asBigInt;
|
|
446
|
+
const asBigInt = sign === "-" ? BigInt(`-${numberGroup1}`) : BigInt(numberGroup1);
|
|
447
|
+
if (asBigInt > BigInt(Number.MAX_SAFE_INTEGER) || asBigInt < BigInt(Number.MIN_SAFE_INTEGER)) return returnValue(asBigInt);
|
|
391
448
|
}
|
|
392
449
|
finalResult = parseInt(numberGroup1);
|
|
393
450
|
}
|
|
394
|
-
if (!numberGroup2)
|
|
451
|
+
if (!numberGroup2) {
|
|
452
|
+
finalResult = sign === "-" ? finalResult * -1 : finalResult;
|
|
453
|
+
if (percentageSuffix && opts.percentage !== "number") finalResult = finalResult / 100;
|
|
454
|
+
return returnValue(finalResult);
|
|
455
|
+
}
|
|
395
456
|
const roundingFactor = opts.round === false ? NaN : parseFloat(`1e${Math.floor(Math.max(0, opts.round))}`);
|
|
396
457
|
if (numberGroup2.startsWith(".") || numberGroup2.startsWith("e") || numberGroup2.startsWith("E")) {
|
|
397
458
|
const decimalValue = parseFloat(`${finalResult}${numberGroup2}`);
|
|
@@ -399,14 +460,34 @@ function numericQuantity(quantity, options = defaultOptions) {
|
|
|
399
460
|
} else if (spaceThenSlashRegex.test(numberGroup2)) {
|
|
400
461
|
const numerator = parseInt(numberGroup1);
|
|
401
462
|
const denominator = parseInt(numberGroup2.replace("/", ""));
|
|
463
|
+
parsedNumerator = numerator;
|
|
464
|
+
parsedDenominator = denominator;
|
|
402
465
|
finalResult = isNaN(roundingFactor) ? numerator / denominator : Math.round(numerator * roundingFactor / denominator) / roundingFactor;
|
|
403
466
|
} else {
|
|
404
467
|
const [numerator, denominator] = numberGroup2.split("/").map((v) => parseInt(v));
|
|
468
|
+
parsedWhole = finalResult;
|
|
469
|
+
parsedNumerator = numerator;
|
|
470
|
+
parsedDenominator = denominator;
|
|
405
471
|
finalResult += isNaN(roundingFactor) ? numerator / denominator : Math.round(numerator * roundingFactor / denominator) / roundingFactor;
|
|
406
472
|
}
|
|
407
|
-
|
|
473
|
+
finalResult = sign === "-" ? finalResult * -1 : finalResult;
|
|
474
|
+
if (percentageSuffix && opts.percentage !== "number") finalResult = isNaN(roundingFactor) ? finalResult / 100 : Math.round(finalResult / 100 * roundingFactor) / roundingFactor;
|
|
475
|
+
return returnValue(finalResult);
|
|
408
476
|
}
|
|
409
477
|
|
|
410
478
|
//#endregion
|
|
411
|
-
|
|
479
|
+
//#region src/isNumericQuantity.ts
|
|
480
|
+
/**
|
|
481
|
+
* Checks if a string represents a valid numeric quantity.
|
|
482
|
+
*
|
|
483
|
+
* Returns `true` if the string can be parsed as a number, `false` otherwise.
|
|
484
|
+
* Accepts the same options as `numericQuantity`.
|
|
485
|
+
*/
|
|
486
|
+
const isNumericQuantity = (quantity, options) => {
|
|
487
|
+
const result = numericQuantity(quantity, _objectSpread2(_objectSpread2({}, options), {}, { verbose: false }));
|
|
488
|
+
return typeof result === "bigint" || !isNaN(result);
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
//#endregion
|
|
492
|
+
export { defaultOptions, isNumericQuantity, normalizeDigits, numericQuantity, numericRegex, numericRegexWithTrailingInvalid, parseRomanNumerals, romanNumeralRegex, romanNumeralUnicodeRegex, romanNumeralUnicodeToAsciiMap, romanNumeralValues, vulgarFractionToAsciiMap, vulgarFractionsRegex };
|
|
412
493
|
//# sourceMappingURL=numeric-quantity.legacy-esm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"numeric-quantity.legacy-esm.js","names":[],"sources":["../src/constants.ts","../src/parseRomanNumerals.ts","../src/numericQuantity.ts"],"sourcesContent":["import type {\n NumericQuantityOptions,\n RomanNumeralAscii,\n RomanNumeralUnicode,\n VulgarFraction,\n} from './types';\n\n// #region Decimal_Number Unicode category\n\n/**\n * Unicode decimal digit block start code points.\n * Each block contains 10 contiguous digits (0-9).\n * This list covers all \\p{Nd} (Decimal_Number) blocks through Unicode 17.0.\n * The drift test in index.test.ts validates completeness against the JS engine.\n */\nconst decimalDigitBlockStarts = [\n 0x0030, // ASCII (0-9)\n 0x0660, // Arabic-Indic\n 0x06f0, // Extended Arabic-Indic (Persian/Urdu)\n 0x07c0, // NKo\n 0x0966, // Devanagari\n 0x09e6, // Bengali\n 0x0a66, // Gurmukhi\n 0x0ae6, // Gujarati\n 0x0b66, // Oriya\n 0x0be6, // Tamil\n 0x0c66, // Telugu\n 0x0ce6, // Kannada\n 0x0d66, // Malayalam\n 0x0de6, // Sinhala Lith\n 0x0e50, // Thai\n 0x0ed0, // Lao\n 0x0f20, // Tibetan\n 0x1040, // Myanmar\n 0x1090, // Myanmar Shan\n 0x17e0, // Khmer\n 0x1810, // Mongolian\n 0x1946, // Limbu\n 0x19d0, // New Tai Lue\n 0x1a80, // Tai Tham Hora\n 0x1a90, // Tai Tham Tham\n 0x1b50, // Balinese\n 0x1bb0, // Sundanese\n 0x1c40, // Lepcha\n 0x1c50, // Ol Chiki\n 0xa620, // Vai\n 0xa8d0, // Saurashtra\n 0xa900, // Kayah Li\n 0xa9d0, // Javanese\n 0xa9f0, // Myanmar Tai Laing\n 0xaa50, // Cham\n 0xabf0, // Meetei Mayek\n 0xff10, // Fullwidth\n 0x104a0, // Osmanya\n 0x10d30, // Hanifi Rohingya\n 0x10d40, // Garay\n 0x11066, // Brahmi\n 0x110f0, // Sora Sompeng\n 0x11136, // Chakma\n 0x111d0, // Sharada\n 0x112f0, // Khudawadi\n 0x11450, // Newa\n 0x114d0, // Tirhuta\n 0x11650, // Modi\n 0x116c0, // Takri\n 0x116d0, // Myanmar Pao\n 0x116da, // Myanmar Eastern Pwo Karen\n 0x11730, // Ahom\n 0x118e0, // Warang Citi\n 0x11950, // Dives Akuru\n 0x11bf0, // Sunuwar\n 0x11c50, // Bhaiksuki\n 0x11d50, // Masaram Gondi\n 0x11da0, // Gunjala Gondi\n 0x11de0, // Tolong Siki\n 0x11f50, // Kawi\n 0x16130, // Gurung Khema\n 0x16a60, // Mro\n 0x16ac0, // Tangsa\n 0x16b50, // Pahawh Hmong\n 0x16d70, // Kirat Rai\n 0x1ccf0, // Outlined Digits\n 0x1d7ce, // Mathematical Bold\n 0x1d7d8, // Mathematical Double-Struck\n 0x1d7e2, // Mathematical Sans-Serif\n 0x1d7ec, // Mathematical Sans-Serif Bold\n 0x1d7f6, // Mathematical Monospace\n 0x1e140, // Nyiakeng Puachue Hmong\n 0x1e2f0, // Wancho\n 0x1e4f0, // Nag Mundari\n 0x1e5f1, // Ol Onal\n 0x1e950, // Adlam\n 0x1fbf0, // Segmented Digits\n] as const;\n\n/**\n * Normalizes non-ASCII decimal digits to ASCII digits.\n * Converts characters from Unicode decimal digit blocks (e.g., Arabic-Indic,\n * Devanagari, Bengali) to their ASCII equivalents (0-9).\n *\n * All current Unicode \\p{Nd} blocks are included in decimalDigitBlockStarts.\n */\nexport const normalizeDigits = (str: string): string =>\n str.replace(/\\p{Nd}/gu, ch => {\n const cp = ch.codePointAt(0)!;\n // ASCII digits (0x0030-0x0039) don't need conversion\n if (cp <= 0x39) return ch;\n // Binary search for the largest block start ≤ cp\n let lo = 0;\n let hi = decimalDigitBlockStarts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >>> 1;\n if (decimalDigitBlockStarts[mid] <= cp) {\n lo = mid;\n } else {\n hi = mid - 1;\n }\n }\n return String(cp - decimalDigitBlockStarts[lo]!);\n });\n\n/**\n * Map of Unicode fraction code points to their ASCII equivalents.\n */\nexport const vulgarFractionToAsciiMap: Record<\n VulgarFraction,\n `${number}/${number | ''}`\n> = {\n '¼': '1/4',\n '½': '1/2',\n '¾': '3/4',\n '⅐': '1/7',\n '⅑': '1/9',\n '⅒': '1/10',\n '⅓': '1/3',\n '⅔': '2/3',\n '⅕': '1/5',\n '⅖': '2/5',\n '⅗': '3/5',\n '⅘': '4/5',\n '⅙': '1/6',\n '⅚': '5/6',\n '⅛': '1/8',\n '⅜': '3/8',\n '⅝': '5/8',\n '⅞': '7/8',\n '⅟': '1/',\n} as const;\n\n/**\n * Captures the individual elements of a numeric string. Commas and underscores are allowed\n * as separators, as long as they appear between digits and are not consecutive.\n *\n * Capture groups:\n *\n * | # | Description | Example(s) |\n * | --- | ------------------------------------------------ | ------------------------------------------------------------------- |\n * | `0` | entire string | `\"2 1/3\"` from `\"2 1/3\"` |\n * | `1` | \"negative\" dash | `\"-\"` from `\"-2 1/3\"` |\n * | `2` | whole number or numerator | `\"2\"` from `\"2 1/3\"`; `\"1\"` from `\"1/3\"` |\n * | `3` | entire fraction, decimal portion, or denominator | `\" 1/3\"` from `\"2 1/3\"`; `\".33\"` from `\"2.33\"`; `\"/3\"` from `\"1/3\"` |\n *\n * _Capture group 2 may include comma/underscore separators._\n *\n * @example\n *\n * ```ts\n * numericRegex.exec(\"1\") // [ \"1\", \"1\", null, null ]\n * numericRegex.exec(\"1.23\") // [ \"1.23\", \"1\", \".23\", null ]\n * numericRegex.exec(\"1 2/3\") // [ \"1 2/3\", \"1\", \" 2/3\", \" 2\" ]\n * numericRegex.exec(\"2/3\") // [ \"2/3\", \"2\", \"/3\", null ]\n * numericRegex.exec(\"2 / 3\") // [ \"2 / 3\", \"2\", \"/ 3\", null ]\n * ```\n */\nexport const numericRegex: RegExp =\n /^(?=-?\\s*\\.\\d|-?\\s*\\d)(-)?\\s*((?:\\d(?:[,_]\\d|\\d)*)*)(([eE][+-]?\\d(?:[,_]\\d|\\d)*)?|\\.\\d(?:[,_]\\d|\\d)*([eE][+-]?\\d(?:[,_]\\d|\\d)*)?|(\\s+\\d(?:[,_]\\d|\\d)*\\s*)?\\s*\\/\\s*\\d(?:[,_]\\d|\\d)*)?$/;\n/**\n * Same as {@link numericRegex}, but allows (and ignores) trailing invalid characters.\n */\nexport const numericRegexWithTrailingInvalid: RegExp =\n /^(?=-?\\s*\\.\\d|-?\\s*\\d)(-)?\\s*((?:\\d(?:[,_]\\d|\\d)*)*)(([eE][+-]?\\d(?:[,_]\\d|\\d)*)?|\\.\\d(?:[,_]\\d|\\d)*([eE][+-]?\\d(?:[,_]\\d|\\d)*)?|(\\s+\\d(?:[,_]\\d|\\d)*\\s*)?\\s*\\/\\s*\\d(?:[,_]\\d|\\d)*)?(?:\\s*[^.\\d/].*)?/;\n\n/**\n * Captures any Unicode vulgar fractions.\n */\nexport const vulgarFractionsRegex: RegExp = /([¼½¾⅐⅑⅒⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞⅟}])/g;\n\n// #endregion\n\n// #region Roman numerals\n\ntype RomanNumeralSequenceFragment =\n | `${RomanNumeralAscii}`\n | `${RomanNumeralAscii}${RomanNumeralAscii}`\n | `${RomanNumeralAscii}${RomanNumeralAscii}${RomanNumeralAscii}`\n | `${RomanNumeralAscii}${RomanNumeralAscii}${RomanNumeralAscii}${RomanNumeralAscii}`;\n\n/**\n * Map of Roman numeral sequences to their decimal equivalents.\n */\nexport const romanNumeralValues: {\n [k in RomanNumeralSequenceFragment]?: number;\n} = {\n MMM: 3000,\n MM: 2000,\n M: 1000,\n CM: 900,\n DCCC: 800,\n DCC: 700,\n DC: 600,\n D: 500,\n CD: 400,\n CCC: 300,\n CC: 200,\n C: 100,\n XC: 90,\n LXXX: 80,\n LXX: 70,\n LX: 60,\n L: 50,\n XL: 40,\n XXX: 30,\n XX: 20,\n XII: 12, // only here for tests; not used in practice\n XI: 11, // only here for tests; not used in practice\n X: 10,\n IX: 9,\n VIII: 8,\n VII: 7,\n VI: 6,\n V: 5,\n IV: 4,\n III: 3,\n II: 2,\n I: 1,\n} as const;\n\n/**\n * Map of Unicode Roman numeral code points to their ASCII equivalents.\n */\nexport const romanNumeralUnicodeToAsciiMap: Record<\n RomanNumeralUnicode,\n keyof typeof romanNumeralValues\n> = {\n // Roman Numeral One (U+2160)\n Ⅰ: 'I',\n // Roman Numeral Two (U+2161)\n Ⅱ: 'II',\n // Roman Numeral Three (U+2162)\n Ⅲ: 'III',\n // Roman Numeral Four (U+2163)\n Ⅳ: 'IV',\n // Roman Numeral Five (U+2164)\n Ⅴ: 'V',\n // Roman Numeral Six (U+2165)\n Ⅵ: 'VI',\n // Roman Numeral Seven (U+2166)\n Ⅶ: 'VII',\n // Roman Numeral Eight (U+2167)\n Ⅷ: 'VIII',\n // Roman Numeral Nine (U+2168)\n Ⅸ: 'IX',\n // Roman Numeral Ten (U+2169)\n Ⅹ: 'X',\n // Roman Numeral Eleven (U+216A)\n Ⅺ: 'XI',\n // Roman Numeral Twelve (U+216B)\n Ⅻ: 'XII',\n // Roman Numeral Fifty (U+216C)\n Ⅼ: 'L',\n // Roman Numeral One Hundred (U+216D)\n Ⅽ: 'C',\n // Roman Numeral Five Hundred (U+216E)\n Ⅾ: 'D',\n // Roman Numeral One Thousand (U+216F)\n Ⅿ: 'M',\n // Small Roman Numeral One (U+2170)\n ⅰ: 'I',\n // Small Roman Numeral Two (U+2171)\n ⅱ: 'II',\n // Small Roman Numeral Three (U+2172)\n ⅲ: 'III',\n // Small Roman Numeral Four (U+2173)\n ⅳ: 'IV',\n // Small Roman Numeral Five (U+2174)\n ⅴ: 'V',\n // Small Roman Numeral Six (U+2175)\n ⅵ: 'VI',\n // Small Roman Numeral Seven (U+2176)\n ⅶ: 'VII',\n // Small Roman Numeral Eight (U+2177)\n ⅷ: 'VIII',\n // Small Roman Numeral Nine (U+2178)\n ⅸ: 'IX',\n // Small Roman Numeral Ten (U+2179)\n ⅹ: 'X',\n // Small Roman Numeral Eleven (U+217A)\n ⅺ: 'XI',\n // Small Roman Numeral Twelve (U+217B)\n ⅻ: 'XII',\n // Small Roman Numeral Fifty (U+217C)\n ⅼ: 'L',\n // Small Roman Numeral One Hundred (U+217D)\n ⅽ: 'C',\n // Small Roman Numeral Five Hundred (U+217E)\n ⅾ: 'D',\n // Small Roman Numeral One Thousand (U+217F)\n ⅿ: 'M',\n} as const;\n\n/**\n * Captures all Unicode Roman numeral code points.\n */\nexport const romanNumeralUnicodeRegex: RegExp =\n /([ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿ])/gi;\n\n/**\n * Captures a valid Roman numeral sequence.\n *\n * Capture groups:\n *\n * | # | Description | Example |\n * | --- | --------------- | ------------------------ |\n * | `0` | Entire string | \"MCCXIV\" from \"MCCXIV\" |\n * | `1` | Thousands | \"M\" from \"MCCXIV\" |\n * | `2` | Hundreds | \"CC\" from \"MCCXIV\" |\n * | `3` | Tens | \"X\" from \"MCCXIV\" |\n * | `4` | Ones | \"IV\" from \"MCCXIV\" |\n *\n * @example\n *\n * ```ts\n * romanNumeralRegex.exec(\"M\") // [ \"M\", \"M\", \"\", \"\", \"\" ]\n * romanNumeralRegex.exec(\"XII\") // [ \"XII\", \"\", \"\", \"X\", \"II\" ]\n * romanNumeralRegex.exec(\"MCCXIV\") // [ \"MCCXIV\", \"M\", \"CC\", \"X\", \"IV\" ]\n * ```\n */\nexport const romanNumeralRegex: RegExp =\n /^(?=[MDCLXVI])(M{0,3})(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$/i;\n\n// #endregion\n\n/**\n * Default options for {@link numericQuantity}.\n */\nexport const defaultOptions: Required<NumericQuantityOptions> = {\n round: 3,\n allowTrailingInvalid: false,\n romanNumerals: false,\n bigIntOnOverflow: false,\n decimalSeparator: '.',\n} as const;\n","import {\n romanNumeralRegex,\n romanNumeralUnicodeRegex,\n romanNumeralUnicodeToAsciiMap,\n romanNumeralValues,\n} from './constants';\n\n// Just a shorthand type alias\ntype RNV = keyof typeof romanNumeralValues;\n\n/**\n * Converts a string of Roman numerals to a number, like `parseInt`\n * for Roman numerals. Uses modern, strict rules (only 1 to 3999).\n *\n * The string can include ASCII representations of Roman numerals\n * or Unicode Roman numeral code points (`U+2160` through `U+217F`).\n */\nexport const parseRomanNumerals = (romanNumerals: string): number => {\n const normalized = `${romanNumerals}`\n // Convert Unicode Roman numerals to ASCII\n .replace(\n romanNumeralUnicodeRegex,\n (_m, rn: keyof typeof romanNumeralUnicodeToAsciiMap) =>\n romanNumeralUnicodeToAsciiMap[rn]\n )\n // Normalize to uppercase (more common for Roman numerals)\n .toUpperCase();\n\n const regexResult = romanNumeralRegex.exec(normalized);\n\n if (!regexResult) {\n return NaN;\n }\n\n const [, thousands, hundreds, tens, ones] = regexResult;\n\n return (\n (romanNumeralValues[thousands as RNV] ?? 0) +\n (romanNumeralValues[hundreds as RNV] ?? 0) +\n (romanNumeralValues[tens as RNV] ?? 0) +\n (romanNumeralValues[ones as RNV] ?? 0)\n );\n};\n","import {\n defaultOptions,\n normalizeDigits,\n numericRegex,\n numericRegexWithTrailingInvalid,\n vulgarFractionToAsciiMap,\n vulgarFractionsRegex,\n} from './constants';\nimport { parseRomanNumerals } from './parseRomanNumerals';\nimport type { NumericQuantityOptions } from './types';\n\nconst spaceThenSlashRegex = /^\\s*\\//;\n\n/**\n * Converts a string to a number, like an enhanced version of `parseFloat`.\n *\n * The string can include mixed numbers, vulgar fractions, or Roman numerals.\n */\nfunction numericQuantity(quantity: string | number): number;\nfunction numericQuantity(\n quantity: string | number,\n options: NumericQuantityOptions & { bigIntOnOverflow: true }\n): number | bigint;\nfunction numericQuantity(\n quantity: string | number,\n options?: NumericQuantityOptions\n): number;\nfunction numericQuantity(\n quantity: string | number,\n options: NumericQuantityOptions = defaultOptions\n) {\n if (typeof quantity === 'number' || typeof quantity === 'bigint') {\n return quantity;\n }\n\n let finalResult = NaN;\n\n // Coerce to string in case qty is a number\n const quantityAsString = normalizeDigits(\n `${quantity}`\n // Convert vulgar fractions to ASCII, with a leading space\n // to keep the whole number and the fraction separate\n .replace(\n vulgarFractionsRegex,\n (_m, vf: keyof typeof vulgarFractionToAsciiMap) =>\n ` ${vulgarFractionToAsciiMap[vf]}`\n )\n // Convert fraction slash to standard slash\n .replace('⁄', '/')\n .trim()\n );\n\n // Bail out if the string was only white space\n if (quantityAsString.length === 0) {\n return NaN;\n }\n\n const opts: Required<NumericQuantityOptions> = {\n ...defaultOptions,\n ...options,\n };\n\n let normalizedString = quantityAsString;\n\n if (opts.decimalSeparator === ',') {\n const commaCount = (quantityAsString.match(/,/g) || []).length;\n if (commaCount === 1) {\n // Treat lone comma as decimal separator; remove all \".\" since they represent\n // thousands/whatever separators\n normalizedString = quantityAsString\n .replaceAll('.', '_')\n .replace(',', '.');\n } else if (commaCount > 1) {\n // The second comma and everything after is \"trailing invalid\"\n if (!opts.allowTrailingInvalid) {\n // Bail out if trailing invalid is not allowed\n return NaN;\n }\n\n const firstCommaIndex = quantityAsString.indexOf(',');\n const secondCommaIndex = quantityAsString.indexOf(\n ',',\n firstCommaIndex + 1\n );\n const beforeSecondComma = quantityAsString\n .substring(0, secondCommaIndex)\n .replaceAll('.', '_')\n .replace(',', '.');\n const afterSecondComma = quantityAsString.substring(secondCommaIndex + 1);\n normalizedString = opts.allowTrailingInvalid\n ? beforeSecondComma + '&' + afterSecondComma\n : beforeSecondComma;\n } else {\n // No comma as decimal separator, so remove all \".\" since they represent\n // thousands/whatever separators\n normalizedString = quantityAsString.replaceAll('.', '_');\n }\n }\n\n const regexResult = (\n opts.allowTrailingInvalid ? numericRegexWithTrailingInvalid : numericRegex\n ).exec(normalizedString);\n\n // If the Arabic numeral regex fails, try Roman numerals\n if (!regexResult) {\n return opts.romanNumerals ? parseRomanNumerals(quantityAsString) : NaN;\n }\n\n const [, dash, ng1temp, ng2temp] = regexResult;\n const numberGroup1 = ng1temp.replaceAll(',', '').replaceAll('_', '');\n const numberGroup2 = ng2temp?.replaceAll(',', '').replaceAll('_', '');\n\n // Numerify capture group 1\n if (!numberGroup1 && numberGroup2 && numberGroup2.startsWith('.')) {\n finalResult = 0;\n } else {\n if (opts.bigIntOnOverflow) {\n const asBigInt = dash ? BigInt(`-${numberGroup1}`) : BigInt(numberGroup1);\n if (\n asBigInt > BigInt(Number.MAX_SAFE_INTEGER) ||\n asBigInt < BigInt(Number.MIN_SAFE_INTEGER)\n ) {\n return asBigInt;\n }\n }\n\n finalResult = parseInt(numberGroup1);\n }\n\n // If capture group 2 is null, then we're dealing with an integer\n // and there is nothing left to process\n if (!numberGroup2) {\n return dash ? finalResult * -1 : finalResult;\n }\n\n const roundingFactor =\n opts.round === false\n ? NaN\n : parseFloat(`1e${Math.floor(Math.max(0, opts.round))}`);\n\n if (\n numberGroup2.startsWith('.') ||\n numberGroup2.startsWith('e') ||\n numberGroup2.startsWith('E')\n ) {\n // If first char of `numberGroup2` is \".\" or \"e\"/\"E\", it's a decimal\n const decimalValue = parseFloat(`${finalResult}${numberGroup2}`);\n finalResult = isNaN(roundingFactor)\n ? decimalValue\n : Math.round(decimalValue * roundingFactor) / roundingFactor;\n } else if (spaceThenSlashRegex.test(numberGroup2)) {\n // If the first non-space char is \"/\" it's a pure fraction (e.g. \"1/2\")\n const numerator = parseInt(numberGroup1);\n const denominator = parseInt(numberGroup2.replace('/', ''));\n finalResult = isNaN(roundingFactor)\n ? numerator / denominator\n : Math.round((numerator * roundingFactor) / denominator) / roundingFactor;\n } else {\n // Otherwise it's a mixed fraction (e.g. \"1 2/3\")\n const fractionArray = numberGroup2.split('/');\n const [numerator, denominator] = fractionArray.map(v => parseInt(v));\n finalResult += isNaN(roundingFactor)\n ? numerator / denominator\n : Math.round((numerator * roundingFactor) / denominator) / roundingFactor;\n }\n\n return dash ? finalResult * -1 : finalResult;\n}\n\nexport { numericQuantity };\n"],"mappings":";;;;;;;AAeA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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W,OAAO,OAAO,iBAAiB,IAC1C,WAAW,OAAO,OAAO,iBAAiB,CAE1C,QAAO;;AAIX,gBAAc,SAAS,aAAa;;AAKtC,KAAI,CAAC,aACH,QAAO,OAAO,cAAc,KAAK;CAGnC,MAAM,iBACJ,KAAK,UAAU,QACX,MACA,WAAW,KAAK,KAAK,MAAM,KAAK,IAAI,GAAG,KAAK,MAAM,CAAC,GAAG;AAE5D,KACE,aAAa,WAAW,IAAI,IAC5B,aAAa,WAAW,IAAI,IAC5B,aAAa,WAAW,IAAI,EAC5B;EAEA,MAAM,eAAe,WAAW,GAAG,cAAc,eAAe;AAChE,gBAAc,MAAM,eAAe,GAC/B,eACA,KAAK,MAAM,eAAe,eAAe,GAAG;YACvC,oBAAoB,KAAK,aAAa,EAAE;EAEjD,MAAM,YAAY,SAAS,aAAa;EACxC,MAAM,cAAc,SAAS,aAAa,QAAQ,KAAK,GAAG,CAAC;AAC3D,gBAAc,MAAM,eAAe,GAC/B,YAAY,cACZ,KAAK,MAAO,YAAY,iBAAkB,YAAY,GAAG;QACxD;EAGL,MAAM,CAAC,WAAW,eADI,aAAa,MAAM,IAAI,CACE,KAAI,MAAK,SAAS,EAAE,CAAC;AACpE,iBAAe,MAAM,eAAe,GAChC,YAAY,cACZ,KAAK,MAAO,YAAY,iBAAkB,YAAY,GAAG;;AAG/D,QAAO,OAAO,cAAc,KAAK"}
|
|
1
|
+
{"version":3,"file":"numeric-quantity.legacy-esm.js","names":[],"sources":["../src/constants.ts","../src/parseRomanNumerals.ts","../src/numericQuantity.ts","../src/isNumericQuantity.ts"],"sourcesContent":["import type {\n NumericQuantityOptions,\n RomanNumeralAscii,\n RomanNumeralUnicode,\n VulgarFraction,\n} from './types';\n\n// #region Decimal_Number Unicode category\n\n/**\n * Unicode decimal digit block start code points.\n * Each block contains 10 contiguous digits (0-9).\n * This list covers all \\p{Nd} (Decimal_Number) blocks through Unicode 17.0.\n * The drift test in index.test.ts validates completeness against the JS engine.\n */\nconst decimalDigitBlockStarts = [\n 0x0030, // ASCII (0-9)\n 0x0660, // Arabic-Indic\n 0x06f0, // Extended Arabic-Indic (Persian/Urdu)\n 0x07c0, // NKo\n 0x0966, // Devanagari\n 0x09e6, // Bengali\n 0x0a66, // Gurmukhi\n 0x0ae6, // Gujarati\n 0x0b66, // Oriya\n 0x0be6, // Tamil\n 0x0c66, // Telugu\n 0x0ce6, // Kannada\n 0x0d66, // Malayalam\n 0x0de6, // Sinhala Lith\n 0x0e50, // Thai\n 0x0ed0, // Lao\n 0x0f20, // Tibetan\n 0x1040, // Myanmar\n 0x1090, // Myanmar Shan\n 0x17e0, // Khmer\n 0x1810, // Mongolian\n 0x1946, // Limbu\n 0x19d0, // New Tai Lue\n 0x1a80, // Tai Tham Hora\n 0x1a90, // Tai Tham Tham\n 0x1b50, // Balinese\n 0x1bb0, // Sundanese\n 0x1c40, // Lepcha\n 0x1c50, // Ol Chiki\n 0xa620, // Vai\n 0xa8d0, // Saurashtra\n 0xa900, // Kayah Li\n 0xa9d0, // Javanese\n 0xa9f0, // Myanmar Tai Laing\n 0xaa50, // Cham\n 0xabf0, // Meetei Mayek\n 0xff10, // Fullwidth\n 0x104a0, // Osmanya\n 0x10d30, // Hanifi Rohingya\n 0x10d40, // Garay\n 0x11066, // Brahmi\n 0x110f0, // Sora Sompeng\n 0x11136, // Chakma\n 0x111d0, // Sharada\n 0x112f0, // Khudawadi\n 0x11450, // Newa\n 0x114d0, // Tirhuta\n 0x11650, // Modi\n 0x116c0, // Takri\n 0x116d0, // Myanmar Pao\n 0x116da, // Myanmar Eastern Pwo Karen\n 0x11730, // Ahom\n 0x118e0, // Warang Citi\n 0x11950, // Dives Akuru\n 0x11bf0, // Sunuwar\n 0x11c50, // Bhaiksuki\n 0x11d50, // Masaram Gondi\n 0x11da0, // Gunjala Gondi\n 0x11de0, // Tolong Siki\n 0x11f50, // Kawi\n 0x16130, // Gurung Khema\n 0x16a60, // Mro\n 0x16ac0, // Tangsa\n 0x16b50, // Pahawh Hmong\n 0x16d70, // Kirat Rai\n 0x1ccf0, // Outlined Digits\n 0x1d7ce, // Mathematical Bold\n 0x1d7d8, // Mathematical Double-Struck\n 0x1d7e2, // Mathematical Sans-Serif\n 0x1d7ec, // Mathematical Sans-Serif Bold\n 0x1d7f6, // Mathematical Monospace\n 0x1e140, // Nyiakeng Puachue Hmong\n 0x1e2f0, // Wancho\n 0x1e4f0, // Nag Mundari\n 0x1e5f1, // Ol Onal\n 0x1e950, // Adlam\n 0x1fbf0, // Segmented Digits\n] as const;\n\n/**\n * Normalizes non-ASCII decimal digits to ASCII digits.\n * Converts characters from Unicode decimal digit blocks (e.g., Arabic-Indic,\n * Devanagari, Bengali) to their ASCII equivalents (0-9).\n *\n * All current Unicode \\p{Nd} blocks are included in decimalDigitBlockStarts.\n */\nexport const normalizeDigits = (str: string): string =>\n str.replace(/\\p{Nd}/gu, ch => {\n const cp = ch.codePointAt(0)!;\n // ASCII digits (0x0030-0x0039) don't need conversion\n if (cp <= 0x39) return ch;\n // Binary search for the largest block start ≤ cp\n let lo = 0;\n let hi = decimalDigitBlockStarts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >>> 1;\n if (decimalDigitBlockStarts[mid] <= cp) {\n lo = mid;\n } else {\n hi = mid - 1;\n }\n }\n return String(cp - decimalDigitBlockStarts[lo]!);\n });\n\n/**\n * Map of Unicode fraction code points to their ASCII equivalents.\n */\nexport const vulgarFractionToAsciiMap: Record<\n VulgarFraction,\n `${number}/${number | ''}`\n> = {\n '¼': '1/4',\n '½': '1/2',\n '¾': '3/4',\n '⅐': '1/7',\n '⅑': '1/9',\n '⅒': '1/10',\n '⅓': '1/3',\n '⅔': '2/3',\n '⅕': '1/5',\n '⅖': '2/5',\n '⅗': '3/5',\n '⅘': '4/5',\n '⅙': '1/6',\n '⅚': '5/6',\n '⅛': '1/8',\n '⅜': '3/8',\n '⅝': '5/8',\n '⅞': '7/8',\n '⅟': '1/',\n} as const;\n\n/**\n * Captures the individual elements of a numeric string. Commas and underscores are allowed\n * as separators, as long as they appear between digits and are not consecutive.\n *\n * Capture groups:\n *\n * | # | Description | Example(s) |\n * | --- | ------------------------------------------------ | ------------------------------------------------------------------- |\n * | `0` | entire string | `\"2 1/3\"` from `\"2 1/3\"` |\n * | `1` | sign (`-` or `+`) | `\"-\"` from `\"-2 1/3\"` |\n * | `2` | whole number or numerator | `\"2\"` from `\"2 1/3\"`; `\"1\"` from `\"1/3\"` |\n * | `3` | entire fraction, decimal portion, or denominator | `\" 1/3\"` from `\"2 1/3\"`; `\".33\"` from `\"2.33\"`; `\"/3\"` from `\"1/3\"` |\n *\n * _Capture group 2 may include comma/underscore separators._\n *\n * @example\n *\n * ```ts\n * numericRegex.exec(\"1\") // [ \"1\", \"1\", null, null ]\n * numericRegex.exec(\"1.23\") // [ \"1.23\", \"1\", \".23\", null ]\n * numericRegex.exec(\"1 2/3\") // [ \"1 2/3\", \"1\", \" 2/3\", \" 2\" ]\n * numericRegex.exec(\"2/3\") // [ \"2/3\", \"2\", \"/3\", null ]\n * numericRegex.exec(\"2 / 3\") // [ \"2 / 3\", \"2\", \"/ 3\", null ]\n * ```\n */\nexport const numericRegex: RegExp =\n /^(?=[-+]?\\s*\\.\\d|[-+]?\\s*\\d)([-+])?\\s*((?:\\d(?:[,_]\\d|\\d)*)*)(([eE][+-]?\\d(?:[,_]\\d|\\d)*)?|\\.\\d(?:[,_]\\d|\\d)*([eE][+-]?\\d(?:[,_]\\d|\\d)*)?|(\\s+\\d(?:[,_]\\d|\\d)*\\s*)?\\s*\\/\\s*\\d(?:[,_]\\d|\\d)*)?$/;\n/**\n * Same as {@link numericRegex}, but allows (and ignores) trailing invalid characters.\n * Capture group 7 contains the trailing invalid portion.\n */\nexport const numericRegexWithTrailingInvalid: RegExp =\n /^(?=[-+]?\\s*\\.\\d|[-+]?\\s*\\d)([-+])?\\s*((?:\\d(?:[,_]\\d|\\d)*)*)(([eE][+-]?\\d(?:[,_]\\d|\\d)*)?|\\.\\d(?:[,_]\\d|\\d)*([eE][+-]?\\d(?:[,_]\\d|\\d)*)?|(\\s+\\d(?:[,_]\\d|\\d)*\\s*)?\\s*\\/\\s*\\d(?:[,_]\\d|\\d)*)?(\\s*[^.\\d/].*)?/;\n\n/**\n * Captures any Unicode vulgar fractions.\n */\nexport const vulgarFractionsRegex: RegExp = /([¼½¾⅐⅑⅒⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞⅟}])/g;\n\n// #endregion\n\n// #region Roman numerals\n\ntype RomanNumeralSequenceFragment =\n | `${RomanNumeralAscii}`\n | `${RomanNumeralAscii}${RomanNumeralAscii}`\n | `${RomanNumeralAscii}${RomanNumeralAscii}${RomanNumeralAscii}`\n | `${RomanNumeralAscii}${RomanNumeralAscii}${RomanNumeralAscii}${RomanNumeralAscii}`;\n\n/**\n * Map of Roman numeral sequences to their decimal equivalents.\n */\nexport const romanNumeralValues: {\n [k in RomanNumeralSequenceFragment]?: number;\n} = {\n MMM: 3000,\n MM: 2000,\n M: 1000,\n CM: 900,\n DCCC: 800,\n DCC: 700,\n DC: 600,\n D: 500,\n CD: 400,\n CCC: 300,\n CC: 200,\n C: 100,\n XC: 90,\n LXXX: 80,\n LXX: 70,\n LX: 60,\n L: 50,\n XL: 40,\n XXX: 30,\n XX: 20,\n XII: 12, // only here for tests; not used in practice\n XI: 11, // only here for tests; not used in practice\n X: 10,\n IX: 9,\n VIII: 8,\n VII: 7,\n VI: 6,\n V: 5,\n IV: 4,\n III: 3,\n II: 2,\n I: 1,\n} as const;\n\n/**\n * Map of Unicode Roman numeral code points to their ASCII equivalents.\n */\nexport const romanNumeralUnicodeToAsciiMap: Record<\n RomanNumeralUnicode,\n keyof typeof romanNumeralValues\n> = {\n // Roman Numeral One (U+2160)\n Ⅰ: 'I',\n // Roman Numeral Two (U+2161)\n Ⅱ: 'II',\n // Roman Numeral Three (U+2162)\n Ⅲ: 'III',\n // Roman Numeral Four (U+2163)\n Ⅳ: 'IV',\n // Roman Numeral Five (U+2164)\n Ⅴ: 'V',\n // Roman Numeral Six (U+2165)\n Ⅵ: 'VI',\n // Roman Numeral Seven (U+2166)\n Ⅶ: 'VII',\n // Roman Numeral Eight (U+2167)\n Ⅷ: 'VIII',\n // Roman Numeral Nine (U+2168)\n Ⅸ: 'IX',\n // Roman Numeral Ten (U+2169)\n Ⅹ: 'X',\n // Roman Numeral Eleven (U+216A)\n Ⅺ: 'XI',\n // Roman Numeral Twelve (U+216B)\n Ⅻ: 'XII',\n // Roman Numeral Fifty (U+216C)\n Ⅼ: 'L',\n // Roman Numeral One Hundred (U+216D)\n Ⅽ: 'C',\n // Roman Numeral Five Hundred (U+216E)\n Ⅾ: 'D',\n // Roman Numeral One Thousand (U+216F)\n Ⅿ: 'M',\n // Small Roman Numeral One (U+2170)\n ⅰ: 'I',\n // Small Roman Numeral Two (U+2171)\n ⅱ: 'II',\n // Small Roman Numeral Three (U+2172)\n ⅲ: 'III',\n // Small Roman Numeral Four (U+2173)\n ⅳ: 'IV',\n // Small Roman Numeral Five (U+2174)\n ⅴ: 'V',\n // Small Roman Numeral Six (U+2175)\n ⅵ: 'VI',\n // Small Roman Numeral Seven (U+2176)\n ⅶ: 'VII',\n // Small Roman Numeral Eight (U+2177)\n ⅷ: 'VIII',\n // Small Roman Numeral Nine (U+2178)\n ⅸ: 'IX',\n // Small Roman Numeral Ten (U+2179)\n ⅹ: 'X',\n // Small Roman Numeral Eleven (U+217A)\n ⅺ: 'XI',\n // Small Roman Numeral Twelve (U+217B)\n ⅻ: 'XII',\n // Small Roman Numeral Fifty (U+217C)\n ⅼ: 'L',\n // Small Roman Numeral One Hundred (U+217D)\n ⅽ: 'C',\n // Small Roman Numeral Five Hundred (U+217E)\n ⅾ: 'D',\n // Small Roman Numeral One Thousand (U+217F)\n ⅿ: 'M',\n} as const;\n\n/**\n * Captures all Unicode Roman numeral code points.\n */\nexport const romanNumeralUnicodeRegex: RegExp =\n /([ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿ])/gi;\n\n/**\n * Captures a valid Roman numeral sequence.\n *\n * Capture groups:\n *\n * | # | Description | Example |\n * | --- | --------------- | ------------------------ |\n * | `0` | Entire string | \"MCCXIV\" from \"MCCXIV\" |\n * | `1` | Thousands | \"M\" from \"MCCXIV\" |\n * | `2` | Hundreds | \"CC\" from \"MCCXIV\" |\n * | `3` | Tens | \"X\" from \"MCCXIV\" |\n * | `4` | Ones | \"IV\" from \"MCCXIV\" |\n *\n * @example\n *\n * ```ts\n * romanNumeralRegex.exec(\"M\") // [ \"M\", \"M\", \"\", \"\", \"\" ]\n * romanNumeralRegex.exec(\"XII\") // [ \"XII\", \"\", \"\", \"X\", \"II\" ]\n * romanNumeralRegex.exec(\"MCCXIV\") // [ \"MCCXIV\", \"M\", \"CC\", \"X\", \"IV\" ]\n * ```\n */\nexport const romanNumeralRegex: RegExp =\n /^(?=[MDCLXVI])(M{0,3})(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$/i;\n\n// #endregion\n\n/**\n * Default options for {@link numericQuantity}.\n */\nexport const defaultOptions: Required<NumericQuantityOptions> = {\n round: 3,\n allowTrailingInvalid: false,\n romanNumerals: false,\n bigIntOnOverflow: false,\n decimalSeparator: '.',\n allowCurrency: false,\n percentage: false,\n verbose: false,\n} as const;\n","import {\n romanNumeralRegex,\n romanNumeralUnicodeRegex,\n romanNumeralUnicodeToAsciiMap,\n romanNumeralValues,\n} from './constants';\n\n// Just a shorthand type alias\ntype RNV = keyof typeof romanNumeralValues;\n\n/**\n * Converts a string of Roman numerals to a number, like `parseInt`\n * for Roman numerals. Uses modern, strict rules (only 1 to 3999).\n *\n * The string can include ASCII representations of Roman numerals\n * or Unicode Roman numeral code points (`U+2160` through `U+217F`).\n */\nexport const parseRomanNumerals = (romanNumerals: string): number => {\n const normalized = `${romanNumerals}`\n // Convert Unicode Roman numerals to ASCII\n .replace(\n romanNumeralUnicodeRegex,\n (_m, rn: keyof typeof romanNumeralUnicodeToAsciiMap) =>\n romanNumeralUnicodeToAsciiMap[rn]\n )\n // Normalize to uppercase (more common for Roman numerals)\n .toUpperCase();\n\n const regexResult = romanNumeralRegex.exec(normalized);\n\n if (!regexResult) {\n return NaN;\n }\n\n const [, thousands, hundreds, tens, ones] = regexResult;\n\n return (\n (romanNumeralValues[thousands as RNV] ?? 0) +\n (romanNumeralValues[hundreds as RNV] ?? 0) +\n (romanNumeralValues[tens as RNV] ?? 0) +\n (romanNumeralValues[ones as RNV] ?? 0)\n );\n};\n","import {\n defaultOptions,\n normalizeDigits,\n numericRegexWithTrailingInvalid,\n vulgarFractionToAsciiMap,\n vulgarFractionsRegex,\n} from './constants';\nimport { parseRomanNumerals } from './parseRomanNumerals';\nimport type {\n NumericQuantityOptions,\n NumericQuantityReturnType,\n NumericQuantityVerboseResult,\n} from './types';\n\nconst spaceThenSlashRegex = /^\\s*\\//;\nconst currencyPrefixRegex = /^([-+]?)\\s*(\\p{Sc}+)\\s*/u;\nconst currencySuffixRegex = /\\s*(\\p{Sc}+)$/u;\nconst percentageSuffixRegex = /%$/;\n\n/**\n * Converts a string to a number, like an enhanced version of `parseFloat`.\n *\n * The string can include mixed numbers, vulgar fractions, or Roman numerals.\n */\nfunction numericQuantity(quantity: string | number): number;\nfunction numericQuantity<T extends NumericQuantityOptions>(\n quantity: string | number,\n options: T\n): NumericQuantityReturnType<T>;\nfunction numericQuantity(\n quantity: string | number,\n options?: NumericQuantityOptions\n): number;\nfunction numericQuantity(\n quantity: string | number,\n options: NumericQuantityOptions = defaultOptions\n): number | bigint | NumericQuantityVerboseResult {\n const opts: Required<NumericQuantityOptions> = {\n ...defaultOptions,\n ...options,\n };\n\n // Metadata for verbose output\n const originalInput = typeof quantity === 'string' ? quantity : `${quantity}`;\n let currencyPrefix: string | undefined;\n let currencySuffix: string | undefined;\n let percentageSuffix: boolean | undefined;\n let trailingInvalid: string | undefined;\n let parsedSign: '-' | '+' | undefined;\n let parsedWhole: number | undefined;\n let parsedNumerator: number | undefined;\n let parsedDenominator: number | undefined;\n\n const buildVerboseResult = (\n value: number | bigint\n ): NumericQuantityVerboseResult => {\n const result: NumericQuantityVerboseResult = { value, input: originalInput };\n if (currencyPrefix) result.currencyPrefix = currencyPrefix;\n if (currencySuffix) result.currencySuffix = currencySuffix;\n if (percentageSuffix) result.percentageSuffix = percentageSuffix;\n if (trailingInvalid) result.trailingInvalid = trailingInvalid;\n if (parsedSign) result.sign = parsedSign;\n if (parsedWhole !== undefined) result.whole = parsedWhole;\n if (parsedNumerator !== undefined) result.numerator = parsedNumerator;\n if (parsedDenominator !== undefined) result.denominator = parsedDenominator;\n return result;\n };\n\n const returnValue = (value: number | bigint) =>\n opts.verbose ? buildVerboseResult(value) : value;\n\n if (typeof quantity === 'number' || typeof quantity === 'bigint') {\n return returnValue(quantity);\n }\n\n let finalResult = NaN;\n let workingString = `${quantity}`;\n\n // Strip currency prefix if allowed (preserving leading dash for negatives)\n if (opts.allowCurrency) {\n const prefixMatch = currencyPrefixRegex.exec(workingString);\n if (prefixMatch && prefixMatch[2]) {\n currencyPrefix = prefixMatch[2];\n // Keep the dash if present, remove currency symbol\n workingString =\n (prefixMatch[1] || '') + workingString.slice(prefixMatch[0].length);\n }\n }\n\n // Strip currency suffix if allowed (before percentage check)\n if (opts.allowCurrency) {\n const suffixMatch = currencySuffixRegex.exec(workingString);\n if (suffixMatch) {\n currencySuffix = suffixMatch[1];\n workingString = workingString.slice(0, -suffixMatch[0].length);\n }\n }\n\n // Strip percentage suffix if option is set\n if (opts.percentage && percentageSuffixRegex.test(workingString)) {\n percentageSuffix = true;\n workingString = workingString.slice(0, -1);\n }\n\n // Coerce to string and normalize\n const quantityAsString = normalizeDigits(\n workingString\n // Convert vulgar fractions to ASCII, with a leading space\n // to keep the whole number and the fraction separate\n .replace(\n vulgarFractionsRegex,\n (_m, vf: keyof typeof vulgarFractionToAsciiMap) =>\n ` ${vulgarFractionToAsciiMap[vf]}`\n )\n // Convert fraction slash to standard slash\n .replace('⁄', '/')\n .trim()\n );\n\n // Bail out if the string was only white space\n if (quantityAsString.length === 0) {\n return returnValue(NaN);\n }\n\n let normalizedString = quantityAsString;\n\n if (opts.decimalSeparator === ',') {\n const commaCount = (quantityAsString.match(/,/g) || []).length;\n if (commaCount === 1) {\n // Treat lone comma as decimal separator; remove all \".\" since they represent\n // thousands/whatever separators\n normalizedString = quantityAsString\n .replaceAll('.', '_')\n .replace(',', '.');\n } else if (commaCount > 1) {\n // The second comma and everything after is \"trailing invalid\"\n if (!opts.allowTrailingInvalid) {\n // Bail out if trailing invalid is not allowed\n return returnValue(NaN);\n }\n\n const firstCommaIndex = quantityAsString.indexOf(',');\n const secondCommaIndex = quantityAsString.indexOf(\n ',',\n firstCommaIndex + 1\n );\n const beforeSecondComma = quantityAsString\n .substring(0, secondCommaIndex)\n .replaceAll('.', '_')\n .replace(',', '.');\n const afterSecondComma = quantityAsString.substring(secondCommaIndex + 1);\n normalizedString = opts.allowTrailingInvalid\n ? beforeSecondComma + '&' + afterSecondComma\n : beforeSecondComma;\n } else {\n // No comma as decimal separator, so remove all \".\" since they represent\n // thousands/whatever separators\n normalizedString = quantityAsString.replaceAll('.', '_');\n }\n }\n\n const regexResult = numericRegexWithTrailingInvalid.exec(normalizedString);\n\n // If the Arabic numeral regex fails, try Roman numerals\n if (!regexResult) {\n return returnValue(\n opts.romanNumerals ? parseRomanNumerals(quantityAsString) : NaN);\n }\n\n // Capture trailing invalid characters: group 7 catches chars starting with\n // [^.\\d/], but the regex (which lacks a $ anchor) may also leave unconsumed\n // input starting with \".\", \"/\", or digits (e.g. \"0.1.2\" or \"1/\").\n const rawTrailing = (\n regexResult[7] || normalizedString.slice(regexResult[0].length)\n ).trim();\n if (rawTrailing) {\n trailingInvalid = rawTrailing;\n if (!opts.allowTrailingInvalid) {\n return returnValue(NaN);\n }\n }\n\n const [, sign, ng1temp, ng2temp] = regexResult;\n if (sign === '-' || sign === '+') parsedSign = sign;\n const numberGroup1 = ng1temp.replaceAll(',', '').replaceAll('_', '');\n const numberGroup2 = ng2temp?.replaceAll(',', '').replaceAll('_', '');\n\n // Numerify capture group 1\n if (!numberGroup1 && numberGroup2 && numberGroup2.startsWith('.')) {\n finalResult = 0;\n } else {\n if (opts.bigIntOnOverflow) {\n const asBigInt = sign === '-' ? BigInt(`-${numberGroup1}`) : BigInt(numberGroup1);\n if (\n asBigInt > BigInt(Number.MAX_SAFE_INTEGER) ||\n asBigInt < BigInt(Number.MIN_SAFE_INTEGER)\n ) {\n // Note: percentage division not applied to bigint overflow\n return returnValue(asBigInt);\n }\n }\n\n finalResult = parseInt(numberGroup1);\n }\n\n // If capture group 2 is null, then we're dealing with an integer\n // and there is nothing left to process\n if (!numberGroup2) {\n finalResult = sign === '-' ? finalResult * -1 : finalResult;\n if (percentageSuffix && opts.percentage !== 'number') {\n finalResult = finalResult / 100;\n }\n return returnValue(finalResult);\n }\n\n const roundingFactor =\n opts.round === false\n ? NaN\n : parseFloat(`1e${Math.floor(Math.max(0, opts.round))}`);\n\n if (\n numberGroup2.startsWith('.') ||\n numberGroup2.startsWith('e') ||\n numberGroup2.startsWith('E')\n ) {\n // If first char of `numberGroup2` is \".\" or \"e\"/\"E\", it's a decimal\n const decimalValue = parseFloat(`${finalResult}${numberGroup2}`);\n finalResult = isNaN(roundingFactor)\n ? decimalValue\n : Math.round(decimalValue * roundingFactor) / roundingFactor;\n } else if (spaceThenSlashRegex.test(numberGroup2)) {\n // If the first non-space char is \"/\" it's a pure fraction (e.g. \"1/2\")\n const numerator = parseInt(numberGroup1);\n const denominator = parseInt(numberGroup2.replace('/', ''));\n parsedNumerator = numerator;\n parsedDenominator = denominator;\n finalResult = isNaN(roundingFactor)\n ? numerator / denominator\n : Math.round((numerator * roundingFactor) / denominator) / roundingFactor;\n } else {\n // Otherwise it's a mixed fraction (e.g. \"1 2/3\")\n const fractionArray = numberGroup2.split('/');\n const [numerator, denominator] = fractionArray.map(v => parseInt(v));\n parsedWhole = finalResult;\n parsedNumerator = numerator;\n parsedDenominator = denominator;\n finalResult += isNaN(roundingFactor)\n ? numerator / denominator\n : Math.round((numerator * roundingFactor) / denominator) / roundingFactor;\n }\n\n finalResult = sign === '-' ? finalResult * -1 : finalResult;\n\n // Apply percentage division if needed\n if (percentageSuffix && opts.percentage !== 'number') {\n finalResult = isNaN(roundingFactor)\n ? finalResult / 100\n : Math.round((finalResult / 100) * roundingFactor) / roundingFactor;\n }\n\n return returnValue(finalResult);\n}\n\nexport { numericQuantity };\n","import { numericQuantity } from './numericQuantity';\nimport type { NumericQuantityOptions } from './types';\n\n/**\n * Checks if a string represents a valid numeric quantity.\n *\n * Returns `true` if the string can be parsed as a number, `false` otherwise.\n * Accepts the same options as `numericQuantity`.\n */\nexport const isNumericQuantity = (\n quantity: string | number,\n options?: NumericQuantityOptions\n): boolean => {\n const result = numericQuantity(quantity, { ...options, verbose: false });\n return typeof result === 'bigint' || !isNaN(result);\n};\n"],"mappings":";;;;;;;AAeA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;AASD,MAAa,mBAAmB,QAC9B,IAAI,wBAAQ,2BAAU,GAAE,OAAM;CAC5B,MAAM,KAAK,GAAG,YAAY,EAAE;AAE5B,KAAI,MAAM,GAAM,QAAO;CAEvB,IAAI,KAAK;CACT,IAAI,KAAK,wBAAwB,SAA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AAM,iBACJ,KAAK,UAAU,QACX,MACA,WAAW,KAAK,KAAK,MAAM,KAAK,IAAI,GAAG,KAAK,MAAM,CAAC,GAAG;AAE5D,KACE,aAAa,WAAW,IAAI,IAC5B,aAAa,WAAW,IAAI,IAC5B,aAAa,WAAW,IAAI,EAC5B;EAEA,MAAM,eAAe,WAAW,GAAG,cAAc,eAAe;AAChE,gBAAc,MAAM,eAAe,GAC/B,eACA,KAAK,MAAM,eAAe,eAAe,GAAG;YACvC,oBAAoB,KAAK,aAAa,EAAE;EAEjD,MAAM,YAAY,SAAS,aAAa;EACxC,MAAM,cAAc,SAAS,aAAa,QAAQ,KAAK,GAAG,CAAC;AAC3D,oBAAkB;AAClB,sBAAoB;AACpB,gBAAc,MAAM,eAAe,GAC/B,YAAY,cACZ,KAAK,MAAO,YAAY,iBAAkB,YAAY,GAAG;QACxD;EAGL,MAAM,CAAC,WAAW,eADI,aAAa,MAAM,IAAI,CACE,KAAI,MAAK,SAAS,EAAE,CAAC;AACpE,gBAAc;AACd,oBAAkB;AAClB,sBAAoB;AACpB,iBAAe,MAAM,eAAe,GAChC,YAAY,cACZ,KAAK,MAAO,YAAY,iBAAkB,YAAY,GAAG;;AAG/D,eAAc,SAAS,MAAM,cAAc,KAAK;AAGhD,KAAI,oBAAoB,KAAK,eAAe,SAC1C,eAAc,MAAM,eAAe,GAC/B,cAAc,MACd,KAAK,MAAO,cAAc,MAAO,eAAe,GAAG;AAGzD,QAAO,YAAY,YAAY;;;;;;;;;;;AC3PjC,MAAa,qBACX,UACA,YACY;CACZ,MAAM,SAAS,gBAAgB,4CAAe,gBAAS,SAAS,SAAQ;AACxE,QAAO,OAAO,WAAW,YAAY,CAAC,MAAM,OAAO"}
|
|
@@ -136,7 +136,7 @@ const vulgarFractionToAsciiMap = {
|
|
|
136
136
|
* | # | Description | Example(s) |
|
|
137
137
|
* | --- | ------------------------------------------------ | ------------------------------------------------------------------- |
|
|
138
138
|
* | `0` | entire string | `"2 1/3"` from `"2 1/3"` |
|
|
139
|
-
* | `1` |
|
|
139
|
+
* | `1` | sign (`-` or `+`) | `"-"` from `"-2 1/3"` |
|
|
140
140
|
* | `2` | whole number or numerator | `"2"` from `"2 1/3"`; `"1"` from `"1/3"` |
|
|
141
141
|
* | `3` | entire fraction, decimal portion, or denominator | `" 1/3"` from `"2 1/3"`; `".33"` from `"2.33"`; `"/3"` from `"1/3"` |
|
|
142
142
|
*
|
|
@@ -152,11 +152,12 @@ const vulgarFractionToAsciiMap = {
|
|
|
152
152
|
* numericRegex.exec("2 / 3") // [ "2 / 3", "2", "/ 3", null ]
|
|
153
153
|
* ```
|
|
154
154
|
*/
|
|
155
|
-
const numericRegex = /^(
|
|
155
|
+
const numericRegex = /^(?=[-+]?\s*\.\d|[-+]?\s*\d)([-+])?\s*((?:\d(?:[,_]\d|\d)*)*)(([eE][+-]?\d(?:[,_]\d|\d)*)?|\.\d(?:[,_]\d|\d)*([eE][+-]?\d(?:[,_]\d|\d)*)?|(\s+\d(?:[,_]\d|\d)*\s*)?\s*\/\s*\d(?:[,_]\d|\d)*)?$/;
|
|
156
156
|
/**
|
|
157
157
|
* Same as {@link numericRegex}, but allows (and ignores) trailing invalid characters.
|
|
158
|
+
* Capture group 7 contains the trailing invalid portion.
|
|
158
159
|
*/
|
|
159
|
-
const numericRegexWithTrailingInvalid = /^(
|
|
160
|
+
const numericRegexWithTrailingInvalid = /^(?=[-+]?\s*\.\d|[-+]?\s*\d)([-+])?\s*((?:\d(?:[,_]\d|\d)*)*)(([eE][+-]?\d(?:[,_]\d|\d)*)?|\.\d(?:[,_]\d|\d)*([eE][+-]?\d(?:[,_]\d|\d)*)?|(\s+\d(?:[,_]\d|\d)*\s*)?\s*\/\s*\d(?:[,_]\d|\d)*)?(\s*[^.\d/].*)?/;
|
|
160
161
|
/**
|
|
161
162
|
* Captures any Unicode vulgar fractions.
|
|
162
163
|
*/
|
|
@@ -269,7 +270,10 @@ const defaultOptions = {
|
|
|
269
270
|
allowTrailingInvalid: false,
|
|
270
271
|
romanNumerals: false,
|
|
271
272
|
bigIntOnOverflow: false,
|
|
272
|
-
decimalSeparator: "."
|
|
273
|
+
decimalSeparator: ".",
|
|
274
|
+
allowCurrency: false,
|
|
275
|
+
percentage: false,
|
|
276
|
+
verbose: false
|
|
273
277
|
};
|
|
274
278
|
|
|
275
279
|
//#endregion
|
|
@@ -292,21 +296,68 @@ const parseRomanNumerals = (romanNumerals) => {
|
|
|
292
296
|
//#endregion
|
|
293
297
|
//#region src/numericQuantity.ts
|
|
294
298
|
const spaceThenSlashRegex = /^\s*\//;
|
|
299
|
+
const currencyPrefixRegex = /^([-+]?)\s*(\p{Sc}+)\s*/u;
|
|
300
|
+
const currencySuffixRegex = /\s*(\p{Sc}+)$/u;
|
|
301
|
+
const percentageSuffixRegex = /%$/;
|
|
295
302
|
function numericQuantity(quantity, options = defaultOptions) {
|
|
296
|
-
if (typeof quantity === "number" || typeof quantity === "bigint") return quantity;
|
|
297
|
-
let finalResult = NaN;
|
|
298
|
-
const quantityAsString = normalizeDigits(`${quantity}`.replace(vulgarFractionsRegex, (_m, vf) => ` ${vulgarFractionToAsciiMap[vf]}`).replace("⁄", "/").trim());
|
|
299
|
-
if (quantityAsString.length === 0) return NaN;
|
|
300
303
|
const opts = {
|
|
301
304
|
...defaultOptions,
|
|
302
305
|
...options
|
|
303
306
|
};
|
|
307
|
+
const originalInput = typeof quantity === "string" ? quantity : `${quantity}`;
|
|
308
|
+
let currencyPrefix;
|
|
309
|
+
let currencySuffix;
|
|
310
|
+
let percentageSuffix;
|
|
311
|
+
let trailingInvalid;
|
|
312
|
+
let parsedSign;
|
|
313
|
+
let parsedWhole;
|
|
314
|
+
let parsedNumerator;
|
|
315
|
+
let parsedDenominator;
|
|
316
|
+
const buildVerboseResult = (value) => {
|
|
317
|
+
const result = {
|
|
318
|
+
value,
|
|
319
|
+
input: originalInput
|
|
320
|
+
};
|
|
321
|
+
if (currencyPrefix) result.currencyPrefix = currencyPrefix;
|
|
322
|
+
if (currencySuffix) result.currencySuffix = currencySuffix;
|
|
323
|
+
if (percentageSuffix) result.percentageSuffix = percentageSuffix;
|
|
324
|
+
if (trailingInvalid) result.trailingInvalid = trailingInvalid;
|
|
325
|
+
if (parsedSign) result.sign = parsedSign;
|
|
326
|
+
if (parsedWhole !== void 0) result.whole = parsedWhole;
|
|
327
|
+
if (parsedNumerator !== void 0) result.numerator = parsedNumerator;
|
|
328
|
+
if (parsedDenominator !== void 0) result.denominator = parsedDenominator;
|
|
329
|
+
return result;
|
|
330
|
+
};
|
|
331
|
+
const returnValue = (value) => opts.verbose ? buildVerboseResult(value) : value;
|
|
332
|
+
if (typeof quantity === "number" || typeof quantity === "bigint") return returnValue(quantity);
|
|
333
|
+
let finalResult = NaN;
|
|
334
|
+
let workingString = `${quantity}`;
|
|
335
|
+
if (opts.allowCurrency) {
|
|
336
|
+
const prefixMatch = currencyPrefixRegex.exec(workingString);
|
|
337
|
+
if (prefixMatch && prefixMatch[2]) {
|
|
338
|
+
currencyPrefix = prefixMatch[2];
|
|
339
|
+
workingString = (prefixMatch[1] || "") + workingString.slice(prefixMatch[0].length);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (opts.allowCurrency) {
|
|
343
|
+
const suffixMatch = currencySuffixRegex.exec(workingString);
|
|
344
|
+
if (suffixMatch) {
|
|
345
|
+
currencySuffix = suffixMatch[1];
|
|
346
|
+
workingString = workingString.slice(0, -suffixMatch[0].length);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (opts.percentage && percentageSuffixRegex.test(workingString)) {
|
|
350
|
+
percentageSuffix = true;
|
|
351
|
+
workingString = workingString.slice(0, -1);
|
|
352
|
+
}
|
|
353
|
+
const quantityAsString = normalizeDigits(workingString.replace(vulgarFractionsRegex, (_m, vf) => ` ${vulgarFractionToAsciiMap[vf]}`).replace("⁄", "/").trim());
|
|
354
|
+
if (quantityAsString.length === 0) return returnValue(NaN);
|
|
304
355
|
let normalizedString = quantityAsString;
|
|
305
356
|
if (opts.decimalSeparator === ",") {
|
|
306
357
|
const commaCount = (quantityAsString.match(/,/g) || []).length;
|
|
307
358
|
if (commaCount === 1) normalizedString = quantityAsString.replaceAll(".", "_").replace(",", ".");
|
|
308
359
|
else if (commaCount > 1) {
|
|
309
|
-
if (!opts.allowTrailingInvalid) return NaN;
|
|
360
|
+
if (!opts.allowTrailingInvalid) return returnValue(NaN);
|
|
310
361
|
const firstCommaIndex = quantityAsString.indexOf(",");
|
|
311
362
|
const secondCommaIndex = quantityAsString.indexOf(",", firstCommaIndex + 1);
|
|
312
363
|
const beforeSecondComma = quantityAsString.substring(0, secondCommaIndex).replaceAll(".", "_").replace(",", ".");
|
|
@@ -314,20 +365,30 @@ function numericQuantity(quantity, options = defaultOptions) {
|
|
|
314
365
|
normalizedString = opts.allowTrailingInvalid ? beforeSecondComma + "&" + afterSecondComma : beforeSecondComma;
|
|
315
366
|
} else normalizedString = quantityAsString.replaceAll(".", "_");
|
|
316
367
|
}
|
|
317
|
-
const regexResult =
|
|
318
|
-
if (!regexResult) return opts.romanNumerals ? parseRomanNumerals(quantityAsString) : NaN;
|
|
319
|
-
const
|
|
368
|
+
const regexResult = numericRegexWithTrailingInvalid.exec(normalizedString);
|
|
369
|
+
if (!regexResult) return returnValue(opts.romanNumerals ? parseRomanNumerals(quantityAsString) : NaN);
|
|
370
|
+
const rawTrailing = (regexResult[7] || normalizedString.slice(regexResult[0].length)).trim();
|
|
371
|
+
if (rawTrailing) {
|
|
372
|
+
trailingInvalid = rawTrailing;
|
|
373
|
+
if (!opts.allowTrailingInvalid) return returnValue(NaN);
|
|
374
|
+
}
|
|
375
|
+
const [, sign, ng1temp, ng2temp] = regexResult;
|
|
376
|
+
if (sign === "-" || sign === "+") parsedSign = sign;
|
|
320
377
|
const numberGroup1 = ng1temp.replaceAll(",", "").replaceAll("_", "");
|
|
321
378
|
const numberGroup2 = ng2temp === null || ng2temp === void 0 ? void 0 : ng2temp.replaceAll(",", "").replaceAll("_", "");
|
|
322
379
|
if (!numberGroup1 && numberGroup2 && numberGroup2.startsWith(".")) finalResult = 0;
|
|
323
380
|
else {
|
|
324
381
|
if (opts.bigIntOnOverflow) {
|
|
325
|
-
const asBigInt =
|
|
326
|
-
if (asBigInt > BigInt(Number.MAX_SAFE_INTEGER) || asBigInt < BigInt(Number.MIN_SAFE_INTEGER)) return asBigInt;
|
|
382
|
+
const asBigInt = sign === "-" ? BigInt(`-${numberGroup1}`) : BigInt(numberGroup1);
|
|
383
|
+
if (asBigInt > BigInt(Number.MAX_SAFE_INTEGER) || asBigInt < BigInt(Number.MIN_SAFE_INTEGER)) return returnValue(asBigInt);
|
|
327
384
|
}
|
|
328
385
|
finalResult = parseInt(numberGroup1);
|
|
329
386
|
}
|
|
330
|
-
if (!numberGroup2)
|
|
387
|
+
if (!numberGroup2) {
|
|
388
|
+
finalResult = sign === "-" ? finalResult * -1 : finalResult;
|
|
389
|
+
if (percentageSuffix && opts.percentage !== "number") finalResult = finalResult / 100;
|
|
390
|
+
return returnValue(finalResult);
|
|
391
|
+
}
|
|
331
392
|
const roundingFactor = opts.round === false ? NaN : parseFloat(`1e${Math.floor(Math.max(0, opts.round))}`);
|
|
332
393
|
if (numberGroup2.startsWith(".") || numberGroup2.startsWith("e") || numberGroup2.startsWith("E")) {
|
|
333
394
|
const decimalValue = parseFloat(`${finalResult}${numberGroup2}`);
|
|
@@ -335,14 +396,37 @@ function numericQuantity(quantity, options = defaultOptions) {
|
|
|
335
396
|
} else if (spaceThenSlashRegex.test(numberGroup2)) {
|
|
336
397
|
const numerator = parseInt(numberGroup1);
|
|
337
398
|
const denominator = parseInt(numberGroup2.replace("/", ""));
|
|
399
|
+
parsedNumerator = numerator;
|
|
400
|
+
parsedDenominator = denominator;
|
|
338
401
|
finalResult = isNaN(roundingFactor) ? numerator / denominator : Math.round(numerator * roundingFactor / denominator) / roundingFactor;
|
|
339
402
|
} else {
|
|
340
403
|
const [numerator, denominator] = numberGroup2.split("/").map((v) => parseInt(v));
|
|
404
|
+
parsedWhole = finalResult;
|
|
405
|
+
parsedNumerator = numerator;
|
|
406
|
+
parsedDenominator = denominator;
|
|
341
407
|
finalResult += isNaN(roundingFactor) ? numerator / denominator : Math.round(numerator * roundingFactor / denominator) / roundingFactor;
|
|
342
408
|
}
|
|
343
|
-
|
|
409
|
+
finalResult = sign === "-" ? finalResult * -1 : finalResult;
|
|
410
|
+
if (percentageSuffix && opts.percentage !== "number") finalResult = isNaN(roundingFactor) ? finalResult / 100 : Math.round(finalResult / 100 * roundingFactor) / roundingFactor;
|
|
411
|
+
return returnValue(finalResult);
|
|
344
412
|
}
|
|
345
413
|
|
|
346
414
|
//#endregion
|
|
347
|
-
|
|
415
|
+
//#region src/isNumericQuantity.ts
|
|
416
|
+
/**
|
|
417
|
+
* Checks if a string represents a valid numeric quantity.
|
|
418
|
+
*
|
|
419
|
+
* Returns `true` if the string can be parsed as a number, `false` otherwise.
|
|
420
|
+
* Accepts the same options as `numericQuantity`.
|
|
421
|
+
*/
|
|
422
|
+
const isNumericQuantity = (quantity, options) => {
|
|
423
|
+
const result = numericQuantity(quantity, {
|
|
424
|
+
...options,
|
|
425
|
+
verbose: false
|
|
426
|
+
});
|
|
427
|
+
return typeof result === "bigint" || !isNaN(result);
|
|
428
|
+
};
|
|
429
|
+
|
|
430
|
+
//#endregion
|
|
431
|
+
export { defaultOptions, isNumericQuantity, normalizeDigits, numericQuantity, numericRegex, numericRegexWithTrailingInvalid, parseRomanNumerals, romanNumeralRegex, romanNumeralUnicodeRegex, romanNumeralUnicodeToAsciiMap, romanNumeralValues, vulgarFractionToAsciiMap, vulgarFractionsRegex };
|
|
348
432
|
//# sourceMappingURL=numeric-quantity.mjs.map
|