format-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.
@@ -1,5 +1,4 @@
1
1
  import { numericQuantity } from "numeric-quantity";
2
-
3
2
  //#region src/constants.ts
4
3
  /**
5
4
  * Default tolerance used by {@link formatQuantity} when determining if a number
@@ -9,16 +8,18 @@ const defaultTolerance = .0075;
9
8
  /**
10
9
  * Default options for {@link formatQuantity}.
11
10
  */
12
- const defaultOptions = {
11
+ const defaultOptions = Object.freeze({
13
12
  vulgarFractions: false,
14
13
  tolerance: defaultTolerance,
15
14
  fractionSlash: false,
16
- romanNumerals: false
17
- };
15
+ romanNumerals: false,
16
+ zeroFormat: "",
17
+ allowTrailingInvalid: true
18
+ });
18
19
  /**
19
20
  * Map of vulgar fractions to their traditional ASCII equivalents.
20
21
  */
21
- const vulgarToAsciiMap = {
22
+ const vulgarToAsciiMap = Object.freeze({
22
23
  "¼": "1/4",
23
24
  "½": "1/2",
24
25
  "¾": "3/4",
@@ -37,59 +38,46 @@ const vulgarToAsciiMap = {
37
38
  "⅜": "3/8",
38
39
  "⅝": "5/8",
39
40
  "⅞": "7/8"
40
- };
41
+ });
41
42
  /**
42
- * Map of "close enough" decimal values to the {@link VulgarFraction} or
43
- * {@link Sixteenth} fraction string matches.
43
+ * Map of "close enough" values to the {@link VulgarFraction} or {@link Sixteenth} fraction
44
+ * string matches. The value +/- the `tolerance` option (or {@link defaultTolerance} if not
45
+ * specified) is considered close enough to match the fraction.
44
46
  */
45
- const fractionDecimalMatches = [
46
- [.33, ""],
47
- [.66, ""],
48
- [.2, ""],
49
- [.4, ""],
50
- [.6, ""],
51
- [.8, ""],
52
- [.166, ""],
53
- [.833, ""],
54
- [.143, ""],
55
- [.111, ""],
56
- [.1, ""],
57
- [.125, ""],
58
- [.25, "¼"],
59
- [.375, ""],
60
- [.5, "½"],
61
- [.625, ""],
62
- [.75, "¾"],
63
- [.875, ""],
64
- [.0625, "1/16"],
65
- [.1875, "3/16"],
66
- [.3125, "5/16"],
67
- [.4375, "7/16"],
68
- [.5625, "9/16"],
69
- [.6875, "11/16"],
70
- [.8125, "13/16"],
71
- [.9375, "15/16"]
72
- ];
73
-
47
+ const fractionDecimalMatches = Object.freeze([
48
+ [1 / 16, "1/16"],
49
+ [1 / 10, ""],
50
+ [1 / 9, ""],
51
+ [1 / 8, ""],
52
+ [1 / 7, ""],
53
+ [1 / 6, ""],
54
+ [3 / 16, "3/16"],
55
+ [1 / 5, ""],
56
+ [1 / 4, "¼"],
57
+ [5 / 16, "5/16"],
58
+ [1 / 3, ""],
59
+ [3 / 8, ""],
60
+ [2 / 5, ""],
61
+ [7 / 16, "7/16"],
62
+ [1 / 2, "½"],
63
+ [9 / 16, "9/16"],
64
+ [3 / 5, ""],
65
+ [5 / 8, ""],
66
+ [2 / 3, ""],
67
+ [11 / 16, "11/16"],
68
+ [3 / 4, "¾"],
69
+ [4 / 5, ""],
70
+ [13 / 16, "13/16"],
71
+ [5 / 6, ""],
72
+ [7 / 8, ""],
73
+ [15 / 16, "15/16"]
74
+ ].map((entry) => Object.freeze(entry)));
74
75
  //#endregion
75
76
  //#region src/formatQuantity.ts
76
- /**
77
- * Determines if two numbers are close enough to consider
78
- * them equal for the purposes of this package.
79
- */
80
- const closeEnough = (n1, n2, tolerance) => Math.abs(n1 - n2) < tolerance;
81
77
  const superscriptDigits = "⁰¹²³⁴⁵⁶⁷⁸⁹";
82
78
  const subscriptDigits = "₀₁₂₃₄₅₆₇₈₉";
83
- const toSuperscript = (s) => {
84
- let r = "";
85
- for (let i = 0; i < s.length; i++) r += superscriptDigits[+s[i]];
86
- return r;
87
- };
88
- const toSubscript = (s) => {
89
- let r = "";
90
- for (let i = 0; i < s.length; i++) r += subscriptDigits[+s[i]];
91
- return r;
92
- };
79
+ const toSuperscript = (s) => [...s].map((c) => superscriptDigits[+c]).join("");
80
+ const toSubscript = (s) => [...s].map((c) => subscriptDigits[+c]).join("");
93
81
  /**
94
82
  * Applies the `vulgarFractions` or `fractionSlash` options as necessary.
95
83
  */
@@ -103,13 +91,25 @@ const getFraction = (vulgarFractionOrSixteenth, { fractionSlash, vulgarFractions
103
91
  return plainFraction;
104
92
  };
105
93
  /**
94
+ * Only `false` (matching disabled) or a non-negative number is a valid
95
+ * `tolerance`. Everything else—negative numbers, `NaN`, non-numbers,
96
+ * `null`, `undefined`—resolves to {@link defaultTolerance}.
97
+ */
98
+ const isValidTolerance = (tolerance) => tolerance === false || typeof tolerance === "number" && tolerance >= 0;
99
+ /**
106
100
  * Merges options object with default options, converting boolean to object if necessary.
107
101
  */
108
- const normalizeOptions = (options) => ({
109
- ...defaultOptions,
110
- ...typeof options === "boolean" ? { vulgarFractions: options } : options
111
- });
112
- const romanNumeralValueKey = [
102
+ const normalizeOptions = (options) => {
103
+ const opts = {
104
+ ...defaultOptions,
105
+ ...typeof options === "boolean" ? { vulgarFractions: options } : typeof options === "object" && options !== null ? options : {}
106
+ };
107
+ if (!isValidTolerance(opts.tolerance)) opts.tolerance = defaultOptions.tolerance;
108
+ if (typeof opts.zeroFormat !== "string") opts.zeroFormat = defaultOptions.zeroFormat;
109
+ if (opts.allowTrailingInvalid !== false) opts.allowTrailingInvalid = true;
110
+ return opts;
111
+ };
112
+ const romanNumeralsByPlace = [
113
113
  "",
114
114
  "C",
115
115
  "CC",
@@ -142,16 +142,17 @@ const romanNumeralValueKey = [
142
142
  "IX"
143
143
  ];
144
144
  /**
145
- * Formats a number as Roman numerals. The number must be between
146
- * 1 and 3999, inclusive.
145
+ * Formats a number or bigint as Roman numerals. The number must be between
146
+ * 1 and 3999, inclusive; any other value—including non-numbers,
147
+ * `NaN`, and non-finite numbers—yields `null`.
147
148
  */
148
- const formatRomanNumerals = (qty) => {
149
- if (typeof qty !== "number" || isNaN(qty)) return null;
150
- if (qty < 1 || qty >= 4e3) return "";
149
+ const formatRomanNumerals = (quantity) => {
150
+ if (typeof quantity !== "number" && typeof quantity !== "bigint" || !(quantity >= 1 && quantity < 4e3)) return null;
151
+ const qty = Number(quantity);
151
152
  const digits = `${Math.floor(qty)}`.split("");
152
153
  let roman = "";
153
154
  let i = 3;
154
- while (i--) roman = `${romanNumeralValueKey[+digits.pop() + i * 10] || ""}${roman}`;
155
+ while (i--) roman = `${romanNumeralsByPlace[+digits.pop() + i * 10] || ""}${roman}`;
155
156
  return `${Array(+digits.join("") + 1).join("M")}${roman}`;
156
157
  };
157
158
  /**
@@ -161,29 +162,47 @@ const formatRomanNumerals = (qty) => {
161
162
  * like "½", pass `true` as the second argument. For other options
162
163
  * see {@link FormatQuantityOptions}.
163
164
  */
164
- const formatQuantity = (qty, options = defaultOptions) => {
165
- const qtyAsNumber = typeof qty === "string" ? numericQuantity(qty, {
166
- round: false,
167
- allowTrailingInvalid: true
165
+ const formatQuantity = (qty, options) => {
166
+ if (typeof qty !== "number" && typeof qty !== "string" && typeof qty !== "bigint") return null;
167
+ const opts = normalizeOptions(options);
168
+ const qtyAsNumber = typeof qty !== "number" && typeof qty !== "bigint" ? numericQuantity(qty, {
169
+ allowTrailingInvalid: opts.allowTrailingInvalid,
170
+ romanNumerals: opts.romanNumerals,
171
+ bigIntOnOverflow: true,
172
+ round: false
168
173
  }) : qty;
169
- if (isNaN(qtyAsNumber) || qtyAsNumber === null) return null;
170
- if (qtyAsNumber === 0) return "";
171
- const opts = normalizeOptions(options ?? defaultOptions);
174
+ if (typeof qtyAsNumber === "number" && isNaN(qtyAsNumber)) return null;
175
+ if (Number(qtyAsNumber) === 0) return opts.zeroFormat;
172
176
  if (opts.romanNumerals) return formatRomanNumerals(qtyAsNumber);
173
- const absoluteValue = Math.abs(qtyAsNumber);
174
- const flooredAbsVal = Math.floor(absoluteValue);
175
- const sign = qtyAsNumber < 0 ? "-" : "";
176
- const wholeStr = flooredAbsVal === 0 ? "" : `${flooredAbsVal}`;
177
- const decimalValue = absoluteValue - flooredAbsVal;
177
+ const absoluteValue = typeof qtyAsNumber === "bigint" ? qtyAsNumber < 0n ? -qtyAsNumber : qtyAsNumber : Math.abs(qtyAsNumber);
178
+ const flooredAbsVal = typeof absoluteValue === "bigint" ? absoluteValue : Math.floor(absoluteValue);
179
+ const wholeNumberStr = `${flooredAbsVal || ""}`;
180
+ const decimalValue = typeof absoluteValue === "bigint" ? 0 : absoluteValue - flooredAbsVal;
178
181
  if (decimalValue === 0) return `${qtyAsNumber}`;
179
- for (const [num, vf] of fractionDecimalMatches) if (closeEnough(decimalValue, num, opts.tolerance)) {
180
- const fraction = getFraction(vf, opts);
182
+ let closestMatch = null;
183
+ let closestMatchDiff = Infinity;
184
+ if (opts.tolerance !== false) for (const [num, vf] of fractionDecimalMatches) {
185
+ const diff = Math.abs(decimalValue - num);
186
+ if (diff < opts.tolerance || diff === 0) {
187
+ if (diff === 0) {
188
+ closestMatch = vf;
189
+ break;
190
+ }
191
+ if (diff < closestMatchDiff) {
192
+ closestMatch = vf;
193
+ closestMatchDiff = diff;
194
+ }
195
+ }
196
+ }
197
+ if (closestMatch) {
198
+ const fraction = getFraction(closestMatch, opts);
181
199
  const isVulgar = fraction in vulgarToAsciiMap;
182
- return `${sign}${wholeStr}${wholeStr ? opts.separator ?? (isVulgar ? "" : " ") : ""}${fraction}`;
200
+ const sep = wholeNumberStr ? opts.separator ?? (isVulgar ? "" : " ") : "";
201
+ return `${qtyAsNumber < 0 ? "-" : ""}${wholeNumberStr}${sep}${fraction}`;
183
202
  }
184
203
  return `${qtyAsNumber}`;
185
204
  };
186
-
187
205
  //#endregion
188
206
  export { defaultOptions, defaultTolerance, formatQuantity, formatRomanNumerals, fractionDecimalMatches, vulgarToAsciiMap };
207
+
189
208
  //# sourceMappingURL=format-quantity.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"format-quantity.mjs","names":[],"sources":["../src/constants.ts","../src/formatQuantity.ts"],"sourcesContent":["import type {\n ResolvedFormatQuantityOptions,\n SimpleFraction,\n Sixteenth,\n VulgarFraction,\n} from './types';\n\n/**\n * Default tolerance used by {@link formatQuantity} when determining if a number\n * is close enough to a fraction value to be considered equivalent.\n */\nexport const defaultTolerance = 0.0075 as const;\n\n/**\n * Default options for {@link formatQuantity}.\n */\nexport const defaultOptions: ResolvedFormatQuantityOptions = {\n vulgarFractions: false,\n tolerance: defaultTolerance,\n fractionSlash: false,\n romanNumerals: false,\n} as const;\n\n/**\n * Map of vulgar fractions to their traditional ASCII equivalents.\n */\nexport const vulgarToAsciiMap: Record<VulgarFraction, SimpleFraction> = {\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} as const;\n\n/**\n * Map of \"close enough\" decimal values to the {@link VulgarFraction} or\n * {@link Sixteenth} fraction string matches.\n */\nexport const fractionDecimalMatches: [number, VulgarFraction | Sixteenth][] = [\n [0.33, '⅓'],\n [0.66, '⅔'],\n [0.2, '⅕'],\n [0.4, '⅖'],\n [0.6, '⅗'],\n [0.8, '⅘'],\n [0.166, '⅙'],\n [0.833, '⅚'],\n [0.143, '⅐'],\n [0.111, '⅑'],\n [0.1, '⅒'],\n [0.125, '⅛'],\n [0.25, '¼'],\n [0.375, '⅜'],\n [0.5, '½'],\n [0.625, '⅝'],\n [0.75, '¾'],\n [0.875, '⅞'],\n [0.0625, '1/16'],\n [0.1875, '3/16'],\n [0.3125, '5/16'],\n [0.4375, '7/16'],\n [0.5625, '9/16'],\n [0.6875, '11/16'],\n [0.8125, '13/16'],\n [0.9375, '15/16'],\n] as const;\n","import { numericQuantity } from 'numeric-quantity';\nimport {\n defaultOptions,\n fractionDecimalMatches,\n vulgarToAsciiMap,\n} from './constants';\nimport type {\n FormatQuantity,\n FormatQuantityOptions,\n ResolvedFormatQuantityOptions,\n SimpleFraction,\n Sixteenth,\n VulgarFraction,\n} from './types';\n\n/**\n * Determines if two numbers are close enough to consider\n * them equal for the purposes of this package.\n */\nconst closeEnough = (n1: number, n2: number, tolerance: number) =>\n Math.abs(n1 - n2) < tolerance;\n\nconst superscriptDigits = '⁰¹²³⁴⁵⁶⁷⁸⁹';\nconst subscriptDigits = '₀₁₂₃₄₅₆₇₈₉';\n\nconst toSuperscript = (s: string) => {\n let r = '';\n for (let i = 0; i < s.length; i++) r += superscriptDigits[+s[i]];\n return r;\n};\nconst toSubscript = (s: string) => {\n let r = '';\n for (let i = 0; i < s.length; i++) r += subscriptDigits[+s[i]];\n return r;\n};\n\n/**\n * Applies the `vulgarFractions` or `fractionSlash` options as necessary.\n */\nconst getFraction = (\n vulgarFractionOrSixteenth: VulgarFraction | Sixteenth,\n { fractionSlash, vulgarFractions }: FormatQuantityOptions\n) => {\n if (vulgarFractions) {\n return vulgarFractionOrSixteenth;\n }\n\n const plainFraction: SimpleFraction =\n vulgarToAsciiMap[vulgarFractionOrSixteenth as VulgarFraction] ??\n vulgarFractionOrSixteenth;\n\n if (fractionSlash) {\n const [num, den] = plainFraction.split('/');\n return `${toSuperscript(num)}⁄${toSubscript(den)}`;\n }\n\n return plainFraction;\n};\n\n/**\n * Merges options object with default options, converting boolean to object if necessary.\n */\nconst normalizeOptions = (\n options: Parameters<FormatQuantity>[1]\n): ResolvedFormatQuantityOptions => ({\n ...defaultOptions,\n ...(typeof options === 'boolean' ? { vulgarFractions: options } : options),\n});\n\n// prettier-ignore\nconst romanNumeralValueKey = [\n \"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\",\n \"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\",\n \"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\",\n] as const;\n\n/**\n * Formats a number as Roman numerals. The number must be between\n * 1 and 3999, inclusive.\n */\nexport const formatRomanNumerals = (qty: number): string | null => {\n if (typeof qty !== 'number' || isNaN(qty)) {\n return null;\n }\n\n if (qty < 1 || qty >= 4000) {\n return '';\n }\n\n const floored = Math.floor(qty);\n\n const digits = `${floored}`.split('');\n let roman = '';\n let i = 3;\n while (i--) {\n roman = `${romanNumeralValueKey[+digits.pop()! + i * 10] || ''}${roman}`;\n }\n\n return `${Array(+digits.join('') + 1).join('M')}${roman}`;\n};\n\n/**\n * Formats a number (or string that appears to be a number)\n * as one would see it written in imperial measurements, e.g.\n * \"1 1/2\" instead of \"1.5\". To use vulgar fraction characters\n * like \"½\", pass `true` as the second argument. For other options\n * see {@link FormatQuantityOptions}.\n */\nexport const formatQuantity: FormatQuantity = (\n qty,\n options = defaultOptions\n) => {\n const qtyAsNumber =\n typeof qty === 'string'\n ? numericQuantity(qty, { round: false, allowTrailingInvalid: true })\n : qty;\n\n // Return `null` if input is not number-like.\n if (isNaN(qtyAsNumber) || qtyAsNumber === null) {\n return null;\n }\n\n // Return an empty string if the value is zero.\n // TODO: Consider a `zeroDisplay` option (e.g. `{ zeroDisplay: \"0\" }`) so\n // callers outside the recipe-ingredient use case can get \"0\" instead of \"\".\n if (qtyAsNumber === 0) {\n return '';\n }\n\n // The default options parameter in the function signature only takes effect\n // if the parameter is `undefined`. The nullish coalescing operator below\n // covers the `null` case.\n const opts = normalizeOptions(options ?? defaultOptions);\n\n if (opts.romanNumerals) {\n return formatRomanNumerals(qtyAsNumber);\n }\n\n const absoluteValue = Math.abs(qtyAsNumber);\n const flooredAbsVal = Math.floor(absoluteValue);\n const sign = qtyAsNumber < 0 ? '-' : '';\n const wholeStr = flooredAbsVal === 0 ? '' : `${flooredAbsVal}`;\n const decimalValue = absoluteValue - flooredAbsVal;\n\n // For integers just return the given value as a string.\n if (decimalValue === 0) {\n return `${qtyAsNumber}`;\n }\n\n for (const [num, vf] of fractionDecimalMatches) {\n if (closeEnough(decimalValue, num, opts.tolerance)) {\n const fraction = getFraction(vf, opts);\n const isVulgar = fraction in vulgarToAsciiMap;\n const sep = wholeStr\n ? (opts.separator ?? (isVulgar ? '' : ' '))\n : '';\n return `${sign}${wholeStr}${sep}${fraction}`;\n }\n }\n\n return `${qtyAsNumber}`;\n};\n"],"mappings":";;;;;;;AAWA,MAAa,mBAAmB;;;;AAKhC,MAAa,iBAAgD;CAC3D,iBAAiB;CACjB,WAAW;CACX,eAAe;CACf,eAAe;CAChB;;;;AAKD,MAAa,mBAA2D;CACtE,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACN;;;;;AAMD,MAAa,yBAAiE;CAC5E,CAAC,KAAM,IAAI;CACX,CAAC,KAAM,IAAI;CACX,CAAC,IAAK,IAAI;CACV,CAAC,IAAK,IAAI;CACV,CAAC,IAAK,IAAI;CACV,CAAC,IAAK,IAAI;CACV,CAAC,MAAO,IAAI;CACZ,CAAC,MAAO,IAAI;CACZ,CAAC,MAAO,IAAI;CACZ,CAAC,MAAO,IAAI;CACZ,CAAC,IAAK,IAAI;CACV,CAAC,MAAO,IAAI;CACZ,CAAC,KAAM,IAAI;CACX,CAAC,MAAO,IAAI;CACZ,CAAC,IAAK,IAAI;CACV,CAAC,MAAO,IAAI;CACZ,CAAC,KAAM,IAAI;CACX,CAAC,MAAO,IAAI;CACZ,CAAC,OAAQ,OAAO;CAChB,CAAC,OAAQ,OAAO;CAChB,CAAC,OAAQ,OAAO;CAChB,CAAC,OAAQ,OAAO;CAChB,CAAC,OAAQ,OAAO;CAChB,CAAC,OAAQ,QAAQ;CACjB,CAAC,OAAQ,QAAQ;CACjB,CAAC,OAAQ,QAAQ;CAClB;;;;;;;;AC3DD,MAAM,eAAe,IAAY,IAAY,cAC3C,KAAK,IAAI,K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O,KAAK,GAAG,GAAG,EAAE,CAAC,KAAK,IAAI,GAAG;;;;;;;;;AAUpD,MAAa,kBACX,KACA,UAAU,mBACP;CACH,MAAM,cACJ,OAAO,QAAQ,WACX,gBAAgB,KAAK;EAAE,OAAO;EAAO,sBAAsB;EAAM,CAAC,GAClE;AAGN,KAAI,MAAM,YAAY,IAAI,gBAAgB,KACxC,QAAO;AAMT,KAAI,gBAAgB,EAClB,QAAO;CAMT,MAAM,OAAO,iBAAiB,WAAW,eAAe;AAExD,KAAI,KAAK,cACP,QAAO,oBAAoB,YAAY;CAGzC,MAAM,gBAAgB,KAAK,IAAI,YAAY;CAC3C,MAAM,gBAAgB,KAAK,MAAM,cAAc;CAC/C,MAAM,OAAO,cAAc,IAAI,MAAM;CACrC,MAAM,WAAW,kBAAkB,IAAI,KAAK,GAAG;CAC/C,MAAM,eAAe,gBAAgB;AAGrC,KAAI,iBAAiB,EACnB,QAAO,GAAG;AAGZ,MAAK,MAAM,CAAC,KAAK,OAAO,uBACtB,KAAI,YAAY,cAAc,KAAK,KAAK,UAAU,EAAE;EAClD,MAAM,WAAW,YAAY,IAAI,KAAK;EACtC,MAAM,WAAW,YAAY;AAI7B,SAAO,GAAG,OAAO,WAHL,WACP,KAAK,cAAc,WAAW,KAAK,OACpC,KAC8B;;AAItC,QAAO,GAAG"}
1
+ {"version":3,"file":"format-quantity.mjs","names":[],"sources":["../src/constants.ts","../src/formatQuantity.ts"],"sourcesContent":["import type {\n ResolvedFormatQuantityOptions,\n SimpleFraction,\n Sixteenth,\n VulgarFraction,\n} from './types';\n\n/**\n * Default tolerance used by {@link formatQuantity} when determining if a number\n * is close enough to a fraction value to be considered equivalent.\n */\nexport const defaultTolerance = 0.0075 as const;\n\n/**\n * Default options for {@link formatQuantity}.\n */\nexport const defaultOptions: Readonly<ResolvedFormatQuantityOptions> = Object.freeze({\n vulgarFractions: false,\n tolerance: defaultTolerance,\n fractionSlash: false,\n romanNumerals: false,\n zeroFormat: '',\n allowTrailingInvalid: true,\n});\n\n/**\n * Map of vulgar fractions to their traditional ASCII equivalents.\n */\nexport const vulgarToAsciiMap: Readonly<Record<VulgarFraction, SimpleFraction>> = Object.freeze({\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});\n\n/**\n * Map of \"close enough\" values to the {@link VulgarFraction} or {@link Sixteenth} fraction\n * string matches. The value +/- the `tolerance` option (or {@link defaultTolerance} if not\n * specified) is considered close enough to match the fraction.\n */\nexport const fractionDecimalMatches: readonly (readonly [number, VulgarFraction | Sixteenth])[] =\n Object.freeze(\n (\n [\n [1 / 16, '1/16'],\n [1 / 10, '⅒'],\n [1 / 9, '⅑'],\n [1 / 8, '⅛'],\n [1 / 7, '⅐'],\n [1 / 6, '⅙'],\n [3 / 16, '3/16'],\n [1 / 5, '⅕'],\n [1 / 4, '¼'],\n [5 / 16, '5/16'],\n [1 / 3, '⅓'],\n [3 / 8, '⅜'],\n [2 / 5, '⅖'],\n [7 / 16, '7/16'],\n [1 / 2, '½'],\n [9 / 16, '9/16'],\n [3 / 5, '⅗'],\n [5 / 8, '⅝'],\n [2 / 3, '⅔'],\n [11 / 16, '11/16'],\n [3 / 4, '¾'],\n [4 / 5, '⅘'],\n [13 / 16, '13/16'],\n [5 / 6, '⅚'],\n [7 / 8, '⅞'],\n [15 / 16, '15/16'],\n ] satisfies [number, VulgarFraction | Sixteenth][]\n ).map(entry => Object.freeze(entry))\n );\n","import { numericQuantity } from 'numeric-quantity';\nimport { defaultOptions, fractionDecimalMatches, vulgarToAsciiMap } from './constants';\nimport type {\n FormatQuantity,\n ResolvedFormatQuantityOptions,\n SimpleFraction,\n Sixteenth,\n VulgarFraction,\n} from './types';\n\nconst superscriptDigits = '⁰¹²³⁴⁵⁶⁷⁸⁹';\nconst subscriptDigits = '₀₁₂₃₄₅₆₇₈₉';\n\n// oxlint-disable-next-line typescript/no-misused-spread\nconst toSuperscript = (s: string) => [...s].map(c => superscriptDigits[+c]).join('');\n// oxlint-disable-next-line typescript/no-misused-spread\nconst toSubscript = (s: string) => [...s].map(c => subscriptDigits[+c]).join('');\n\n/**\n * Applies the `vulgarFractions` or `fractionSlash` options as necessary.\n */\nconst getFraction = (\n vulgarFractionOrSixteenth: VulgarFraction | Sixteenth,\n { fractionSlash, vulgarFractions }: ResolvedFormatQuantityOptions\n) => {\n if (vulgarFractions) {\n return vulgarFractionOrSixteenth;\n }\n\n const plainFraction: SimpleFraction =\n vulgarToAsciiMap[vulgarFractionOrSixteenth as VulgarFraction] ?? vulgarFractionOrSixteenth;\n\n if (fractionSlash) {\n const [num, den] = plainFraction.split('/');\n return `${toSuperscript(num)}⁄${toSubscript(den)}`;\n }\n\n return plainFraction;\n};\n\n/**\n * Only `false` (matching disabled) or a non-negative number is a valid\n * `tolerance`. Everything else—negative numbers, `NaN`, non-numbers,\n * `null`, `undefined`—resolves to {@link defaultTolerance}.\n */\nconst isValidTolerance = (tolerance: unknown): tolerance is number | false =>\n tolerance === false || (typeof tolerance === 'number' && tolerance >= 0);\n\n/**\n * Merges options object with default options, converting boolean to object if necessary.\n */\nconst normalizeOptions = (\n options: Parameters<FormatQuantity>[1]\n): ResolvedFormatQuantityOptions => {\n const opts: ResolvedFormatQuantityOptions = {\n ...defaultOptions,\n ...(typeof options === 'boolean'\n ? { vulgarFractions: options }\n : typeof options === 'object' && options !== null\n ? options\n : {}),\n };\n\n if (!isValidTolerance(opts.tolerance)) {\n opts.tolerance = defaultOptions.tolerance;\n }\n\n if (typeof opts.zeroFormat !== 'string') {\n opts.zeroFormat = defaultOptions.zeroFormat;\n }\n\n if (opts.allowTrailingInvalid !== false) {\n opts.allowTrailingInvalid = true;\n }\n\n return opts;\n};\n\n// oxfmt-ignore\nconst romanNumeralsByPlace = [\n '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',\n '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',\n '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX',\n] as const;\n\n/**\n * Formats a number or bigint as Roman numerals. The number must be between\n * 1 and 3999, inclusive; any other value—including non-numbers,\n * `NaN`, and non-finite numbers—yields `null`.\n */\nexport const formatRomanNumerals = (quantity: number | bigint): string | null => {\n if (\n (typeof quantity !== 'number' && typeof quantity !== 'bigint') ||\n !(quantity >= 1 && quantity < 4000)\n ) {\n return null;\n }\n\n const qty = Number(quantity);\n\n const floored = Math.floor(qty);\n\n const digits = `${floored}`.split('');\n let roman = '';\n let i = 3;\n while (i--) {\n roman = `${romanNumeralsByPlace[+digits.pop()! + i * 10] || ''}${roman}`;\n }\n\n return `${Array(+digits.join('') + 1).join('M')}${roman}`;\n};\n\n/**\n * Formats a number (or string that appears to be a number)\n * as one would see it written in imperial measurements, e.g.\n * \"1 1/2\" instead of \"1.5\". To use vulgar fraction characters\n * like \"½\", pass `true` as the second argument. For other options\n * see {@link FormatQuantityOptions}.\n */\nexport const formatQuantity: FormatQuantity = (qty, options) => {\n // Only numbers, bigints, and strings are accepted. Anything else (objects, booleans,\n // nullish, arrays like `[1]` that would coerce to a numeric string) is\n // rejected up front so off-type inputs behave consistently.\n if (typeof qty !== 'number' && typeof qty !== 'string' && typeof qty !== 'bigint') {\n return null;\n }\n\n const opts = normalizeOptions(options);\n\n const qtyAsNumber =\n typeof qty !== 'number' && typeof qty !== 'bigint'\n ? numericQuantity(qty, {\n allowTrailingInvalid: opts.allowTrailingInvalid,\n romanNumerals: opts.romanNumerals,\n bigIntOnOverflow: true,\n round: false,\n })\n : qty;\n\n // Return `null` if input is not number-like.\n if (typeof qtyAsNumber === 'number' && isNaN(qtyAsNumber)) {\n return null;\n }\n\n // Return empty string (or configured `zeroFormat`) if the value is zero.\n if (Number(qtyAsNumber) === 0) {\n return opts.zeroFormat;\n }\n\n if (opts.romanNumerals) {\n return formatRomanNumerals(qtyAsNumber);\n }\n\n const absoluteValue =\n typeof qtyAsNumber === 'bigint'\n ? qtyAsNumber < 0n\n ? -qtyAsNumber\n : qtyAsNumber\n : Math.abs(qtyAsNumber);\n const flooredAbsVal =\n typeof absoluteValue === 'bigint' ? absoluteValue : Math.floor(absoluteValue);\n const wholeNumberStr = `${flooredAbsVal || ''}`;\n const decimalValue =\n typeof absoluteValue === 'bigint' ? 0 : absoluteValue - (flooredAbsVal as number);\n\n // For integers just return the given value as a string.\n if (decimalValue === 0) {\n return `${qtyAsNumber}`;\n }\n\n let closestMatch: VulgarFraction | Sixteenth | null = null;\n let closestMatchDiff = Infinity;\n // `tolerance: false` disables fraction matching entirely.\n if (opts.tolerance !== false) {\n for (const [num, vf] of fractionDecimalMatches) {\n const diff = Math.abs(decimalValue - num);\n // `diff === 0` keeps exact quotients matching even at `tolerance: 0`.\n if (diff < opts.tolerance || diff === 0) {\n if (diff === 0) {\n closestMatch = vf;\n break;\n }\n if (diff < closestMatchDiff) {\n closestMatch = vf;\n closestMatchDiff = diff;\n }\n }\n }\n }\n\n if (closestMatch) {\n const fraction = getFraction(closestMatch, opts);\n const isVulgar = fraction in vulgarToAsciiMap;\n const sep = wholeNumberStr ? (opts.separator ?? (isVulgar ? '' : ' ')) : '';\n return `${qtyAsNumber < 0 ? '-' : ''}${wholeNumberStr}${sep}${fraction}`;\n }\n\n return `${qtyAsNumber}`;\n};\n"],"mappings":";;;;;;AAWA,MAAa,mBAAmB;;;;AAKhC,MAAa,iBAA0D,OAAO,OAAO;CACnF,iBAAiB;CACjB,WAAW;CACX,eAAe;CACf,eAAe;CACf,YAAY;CACZ,sBAAsB;AACxB,CAAC;;;;AAKD,MAAa,mBAAqE,OAAO,OAAO;CAC9F,KAAK;CACL,KAAK;CACL,KAA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,IAAI;EAC/C,MAAM,WAAW,YAAY;EAC7B,MAAM,MAAM,iBAAkB,KAAK,cAAc,WAAW,KAAK,OAAQ;EACzE,OAAO,GAAG,cAAc,IAAI,MAAM,KAAK,iBAAiB,MAAM;CAChE;CAEA,OAAO,GAAG;AACZ"}
@@ -1,107 +1,131 @@
1
1
  //#region src/types.d.ts
2
2
  interface FormatQuantityOptions {
3
3
  /**
4
- * Output vulgar fractions, like "½" instead of "1/2", when appropriate.
5
- * Overrides the `fractionSlash` option.
6
- */
4
+ * Output vulgar fractions, like "½" instead of "1/2", when appropriate.
5
+ * Overrides the `fractionSlash` option.
6
+ *
7
+ * @default false
8
+ */
7
9
  vulgarFractions?: boolean;
8
10
  /**
9
- * Amount by which a number can deviate from the calculated quotient to be
10
- * considered a match. For example, 0.66 is close enough to 2 ÷ 3 (which
11
- * is 0.66666... repeating) to be considered equivalent so the function
12
- * will return "2/3". The smaller this number, the higher the likelihood that
13
- * the function will return a decimal instead of a fraction or mixed number.
14
- *
15
- * @default 0.0075
16
- */
17
- tolerance?: number;
11
+ * Amount by which a number can deviate from the calculated quotient to be
12
+ * considered a match. For example, 0.66 is close enough to 2 ÷ 3 (which
13
+ * is 0.66666... repeating) to be considered equivalent so the function
14
+ * will return "2/3". The smaller this number, the higher the likelihood that
15
+ * the function will return a decimal instead of a fraction or mixed number.
16
+ *
17
+ * `0` means only exact quotients match. `false` disables fraction matching
18
+ * entirely, so decimal values are always returned as decimals.
19
+ *
20
+ * Any other value—negative, non-numeric, `NaN`, `null`, `undefined`—resolves
21
+ * to the default.
22
+ *
23
+ * @default 0.0075
24
+ */
25
+ tolerance?: number | false;
18
26
  /**
19
- * Output the fraction slash character (⁄) instead of the "solidus"
20
- * slash (/) for fractions. Results appear like "1⁄2" instead of "1/2".
21
- * Overridden by the `vulgarFractions` option.
22
- */
27
+ * Output the fraction slash character (⁄) instead of the "solidus"
28
+ * slash (/) for fractions. Results appear like "1⁄2" instead of "1/2".
29
+ * Overridden by the `vulgarFractions` option.
30
+ *
31
+ * @default false
32
+ */
23
33
  fractionSlash?: boolean;
24
34
  /**
25
- * Output in Roman numerals. Provided value must be between 1 and 3999, inclusive.
26
- * Decimal values will be ignored (`Math.floor` is used to remove them). Overrides
27
- * all other options.
28
- */
35
+ * Output in Roman numerals. Provided value must be between 1 and 3999, inclusive.
36
+ * Decimal values will be ignored (`Math.floor` is used to remove them). Overrides
37
+ * all other options.
38
+ *
39
+ * @default false
40
+ */
29
41
  romanNumerals?: boolean;
30
42
  /**
31
- * String to place between the whole number and fraction parts. When not specified,
32
- * defaults to `" "` for ASCII and fraction-slash fractions, and `""` for vulgar
33
- * fractions (preserving the standard typographic convention of no space before
34
- * vulgar fraction characters).
35
- */
43
+ * String to place between the whole number and fraction parts. When not specified,
44
+ * defaults to `" "` for ASCII and fraction-slash fractions, and `""` for vulgar
45
+ * fractions (preserving the standard typographic convention of no space before
46
+ * vulgar fraction characters).
47
+ */
36
48
  separator?: string;
49
+ /**
50
+ * String to return when the input evaluates numerically to zero.
51
+ *
52
+ * @default "" (empty string)
53
+ */
54
+ zeroFormat?: string;
55
+ /**
56
+ * If `qty` is a string, allow trailing invalid characters after the numeric portion.
57
+ *
58
+ * @default true
59
+ */
60
+ allowTrailingInvalid?: boolean;
37
61
  }
38
62
  /**
39
- * {@link FormatQuantityOptions} with all properties resolved to their
40
- * default values, except {@link FormatQuantityOptions.separator | separator}
41
- * which remains optional so that unset vs explicitly-set can be distinguished.
42
- */
63
+ * {@link FormatQuantityOptions} with all properties resolved to their
64
+ * default values, except {@link FormatQuantityOptions.separator | separator}
65
+ * which remains optional so that unset vs explicitly-set can be distinguished.
66
+ */
43
67
  type ResolvedFormatQuantityOptions = Required<Omit<FormatQuantityOptions, "separator">> & Pick<FormatQuantityOptions, "separator">;
44
68
  /**
45
- * Function signature of {@link formatQuantity}.
46
- */
69
+ * Function signature of {@link formatQuantity}.
70
+ */
47
71
  interface FormatQuantity {
48
- (qty: string | number, options?: boolean | FormatQuantityOptions): string | null;
72
+ (qty: string | number | bigint, options?: boolean | FormatQuantityOptions): string | null;
49
73
  }
50
74
  /** Any numeric character. */
51
75
  type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
52
76
  /** Any numeric character except '0'. */
53
77
  type NonZeroDigit = Exclude<Digit, "0">;
54
78
  /**
55
- * Fraction string with either one or two numeric characters in both the
56
- * numerator and denominator (but not two characters in the numerator while
57
- * the denominator only has one).
58
- */
79
+ * Fraction string with either one or two numeric characters in both the
80
+ * numerator and denominator (but not two characters in the numerator while
81
+ * the denominator only has one).
82
+ */
59
83
  type SimpleFraction = `${NonZeroDigit}/${NonZeroDigit}` | `${NonZeroDigit}/${NonZeroDigit}${Digit}` | `${NonZeroDigit}${Digit}/${NonZeroDigit}${Digit}`;
60
84
  /**
61
- * Odd numerator sixteenth fraction strings.
62
- */
85
+ * Odd numerator sixteenth fraction strings.
86
+ */
63
87
  type Sixteenth = `${"1" | "3" | "5" | "7" | "9" | "11" | "13" | "15"}/16`;
64
88
  /**
65
- * Unicode vulgar fraction code points.
66
- */
89
+ * Unicode vulgar fraction code points.
90
+ */
67
91
  type VulgarFraction = "¼" | "½" | "¾" | "⅐" | "⅑" | "⅒" | "⅓" | "⅔" | "⅕" | "⅖" | "⅗" | "⅘" | "⅙" | "⅚" | "⅛" | "⅜" | "⅝" | "⅞";
68
- /** @hidden */
69
- type FormatQuantityTests = Record<string, ([Parameters<FormatQuantity>[0], ReturnType<FormatQuantity>] | [Parameters<FormatQuantity>[0], ReturnType<FormatQuantity>, Parameters<FormatQuantity>[1]])[]>;
70
92
  //#endregion
71
93
  //#region src/constants.d.ts
72
94
  /**
73
- * Default tolerance used by {@link formatQuantity} when determining if a number
74
- * is close enough to a fraction value to be considered equivalent.
75
- */
95
+ * Default tolerance used by {@link formatQuantity} when determining if a number
96
+ * is close enough to a fraction value to be considered equivalent.
97
+ */
76
98
  declare const defaultTolerance: 0.0075;
77
99
  /**
78
- * Default options for {@link formatQuantity}.
79
- */
80
- declare const defaultOptions: ResolvedFormatQuantityOptions;
100
+ * Default options for {@link formatQuantity}.
101
+ */
102
+ declare const defaultOptions: Readonly<ResolvedFormatQuantityOptions>;
81
103
  /**
82
- * Map of vulgar fractions to their traditional ASCII equivalents.
83
- */
84
- declare const vulgarToAsciiMap: Record<VulgarFraction, SimpleFraction>;
104
+ * Map of vulgar fractions to their traditional ASCII equivalents.
105
+ */
106
+ declare const vulgarToAsciiMap: Readonly<Record<VulgarFraction, SimpleFraction>>;
85
107
  /**
86
- * Map of "close enough" decimal values to the {@link VulgarFraction} or
87
- * {@link Sixteenth} fraction string matches.
88
- */
89
- declare const fractionDecimalMatches: [number, VulgarFraction | Sixteenth][];
108
+ * Map of "close enough" values to the {@link VulgarFraction} or {@link Sixteenth} fraction
109
+ * string matches. The value +/- the `tolerance` option (or {@link defaultTolerance} if not
110
+ * specified) is considered close enough to match the fraction.
111
+ */
112
+ declare const fractionDecimalMatches: readonly (readonly [number, VulgarFraction | Sixteenth])[];
90
113
  //#endregion
91
114
  //#region src/formatQuantity.d.ts
92
115
  /**
93
- * Formats a number as Roman numerals. The number must be between
94
- * 1 and 3999, inclusive.
95
- */
96
- declare const formatRomanNumerals: (qty: number) => string | null;
116
+ * Formats a number or bigint as Roman numerals. The number must be between
117
+ * 1 and 3999, inclusive; any other value—including non-numbers,
118
+ * `NaN`, and non-finite numbers—yields `null`.
119
+ */
120
+ declare const formatRomanNumerals: (quantity: number | bigint) => string | null;
97
121
  /**
98
- * Formats a number (or string that appears to be a number)
99
- * as one would see it written in imperial measurements, e.g.
100
- * "1 1/2" instead of "1.5". To use vulgar fraction characters
101
- * like "½", pass `true` as the second argument. For other options
102
- * see {@link FormatQuantityOptions}.
103
- */
122
+ * Formats a number (or string that appears to be a number)
123
+ * as one would see it written in imperial measurements, e.g.
124
+ * "1 1/2" instead of "1.5". To use vulgar fraction characters
125
+ * like "½", pass `true` as the second argument. For other options
126
+ * see {@link FormatQuantityOptions}.
127
+ */
104
128
  declare const formatQuantity: FormatQuantity;
105
129
  //#endregion
106
- export { Digit, FormatQuantity, FormatQuantityOptions, FormatQuantityTests, NonZeroDigit, ResolvedFormatQuantityOptions, SimpleFraction, Sixteenth, VulgarFraction, defaultOptions, defaultTolerance, formatQuantity, formatRomanNumerals, fractionDecimalMatches, vulgarToAsciiMap };
130
+ export { Digit, FormatQuantity, FormatQuantityOptions, NonZeroDigit, ResolvedFormatQuantityOptions, SimpleFraction, Sixteenth, VulgarFraction, defaultOptions, defaultTolerance, formatQuantity, formatRomanNumerals, fractionDecimalMatches, vulgarToAsciiMap };
107
131
  //# sourceMappingURL=format-quantity.production.d.mts.map
@@ -1,2 +1,2 @@
1
- import{numericQuantity as e}from"numeric-quantity";const t=.0075,n={vulgarFractions:!1,tolerance:t,fractionSlash:!1,romanNumerals:!1},r={"¼":`1/4`,"½":`1/2`,"¾":`3/4`,"⅐":`1/7`,"⅑":`1/9`,"⅒":`1/10`,"⅓":`1/3`,"⅔":`2/3`,"⅕":`1/5`,"⅖":`2/5`,"⅗":`3/5`,"⅘":`4/5`,"⅙":`1/6`,"⅚":`5/6`,"⅛":`1/8`,"⅜":`3/8`,"⅝":`5/8`,"⅞":`7/8`},i=[[.33,`⅓`],[.66,`⅔`],[.2,`⅕`],[.4,`⅖`],[.6,`⅗`],[.8,`⅘`],[.166,`⅙`],[.833,`⅚`],[.143,`⅐`],[.111,`⅑`],[.1,`⅒`],[.125,`⅛`],[.25,`¼`],[.375,`⅜`],[.5,`½`],[.625,`⅝`],[.75,`¾`],[.875,`⅞`],[.0625,`1/16`],[.1875,`3/16`],[.3125,`5/16`],[.4375,`7/16`],[.5625,`9/16`],[.6875,`11/16`],[.8125,`13/16`],[.9375,`15/16`]],a=(e,t,n)=>Math.abs(e-t)<n,o=e=>{let t=``;for(let n=0;n<e.length;n++)t+=`⁰¹²³⁴⁵⁶⁷⁸⁹`[+e[n]];return t},s=e=>{let t=``;for(let n=0;n<e.length;n++)t+=`₀₁₂₃₄₅₆₇₈₉`[+e[n]];return t},c=(e,{fractionSlash:t,vulgarFractions:n})=>{if(n)return e;let i=r[e]??e;if(t){let[e,t]=i.split(`/`);return`${o(e)}⁄${s(t)}`}return i},l=e=>({...n,...typeof e==`boolean`?{vulgarFractions:e}:e}),u=`.C.CC.CCC.CD.D.DC.DCC.DCCC.CM..X.XX.XXX.XL.L.LX.LXX.LXXX.XC..I.II.III.IV.V.VI.VII.VIII.IX`.split(`.`),d=e=>{if(typeof e!=`number`||isNaN(e))return null;if(e<1||e>=4e3)return``;let t=`${Math.floor(e)}`.split(``),n=``,r=3;for(;r--;)n=`${u[+t.pop()+r*10]||``}${n}`;return`${Array(+t.join(``)+1).join(`M`)}${n}`},f=(t,o=n)=>{let s=typeof t==`string`?e(t,{round:!1,allowTrailingInvalid:!0}):t;if(isNaN(s)||s===null)return null;if(s===0)return``;let u=l(o??n);if(u.romanNumerals)return d(s);let f=Math.abs(s),p=Math.floor(f),m=s<0?`-`:``,h=p===0?``:`${p}`,g=f-p;if(g===0)return`${s}`;for(let[e,t]of i)if(a(g,e,u.tolerance)){let e=c(t,u),n=e in r;return`${m}${h}${h?u.separator??(n?``:` `):``}${e}`}return`${s}`};export{n as defaultOptions,t as defaultTolerance,f as formatQuantity,d as formatRomanNumerals,i as fractionDecimalMatches,r as vulgarToAsciiMap};
1
+ import{numericQuantity as e}from"numeric-quantity";const t=.0075,n=Object.freeze({vulgarFractions:!1,tolerance:t,fractionSlash:!1,romanNumerals:!1,zeroFormat:``,allowTrailingInvalid:!0}),r=Object.freeze({"¼":`1/4`,"½":`1/2`,"¾":`3/4`,"⅐":`1/7`,"⅑":`1/9`,"⅒":`1/10`,"⅓":`1/3`,"⅔":`2/3`,"⅕":`1/5`,"⅖":`2/5`,"⅗":`3/5`,"⅘":`4/5`,"⅙":`1/6`,"⅚":`5/6`,"⅛":`1/8`,"⅜":`3/8`,"⅝":`5/8`,"⅞":`7/8`}),i=Object.freeze([[1/16,`1/16`],[1/10,`⅒`],[1/9,`⅑`],[1/8,`⅛`],[1/7,`⅐`],[1/6,`⅙`],[3/16,`3/16`],[1/5,`⅕`],[1/4,`¼`],[5/16,`5/16`],[1/3,`⅓`],[3/8,`⅜`],[2/5,`⅖`],[7/16,`7/16`],[1/2,`½`],[9/16,`9/16`],[3/5,`⅗`],[5/8,`⅝`],[2/3,`⅔`],[11/16,`11/16`],[3/4,`¾`],[4/5,`⅘`],[13/16,`13/16`],[5/6,`⅚`],[7/8,`⅞`],[15/16,`15/16`]].map(e=>Object.freeze(e))),a=e=>[...e].map(e=>`⁰¹²³⁴⁵⁶⁷⁸⁹`[+e]).join(``),o=e=>[...e].map(e=>`₀₁₂₃₄₅₆₇₈₉`[+e]).join(``),s=(e,{fractionSlash:t,vulgarFractions:n})=>{if(n)return e;let i=r[e]??e;if(t){let[e,t]=i.split(`/`);return`${a(e)}⁄${o(t)}`}return i},c=e=>e===!1||typeof e==`number`&&e>=0,l=e=>{let t={...n,...typeof e==`boolean`?{vulgarFractions:e}:typeof e==`object`&&e?e:{}};return c(t.tolerance)||(t.tolerance=n.tolerance),typeof t.zeroFormat!=`string`&&(t.zeroFormat=n.zeroFormat),t.allowTrailingInvalid!==!1&&(t.allowTrailingInvalid=!0),t},u=`.C.CC.CCC.CD.D.DC.DCC.DCCC.CM..X.XX.XXX.XL.L.LX.LXX.LXXX.XC..I.II.III.IV.V.VI.VII.VIII.IX`.split(`.`),d=e=>{if(typeof e!=`number`&&typeof e!=`bigint`||!(e>=1&&e<4e3))return null;let t=Number(e),n=`${Math.floor(t)}`.split(``),r=``,i=3;for(;i--;)r=`${u[+n.pop()+i*10]||``}${r}`;return`${Array(+n.join(``)+1).join(`M`)}${r}`},f=(t,n)=>{if(typeof t!=`number`&&typeof t!=`string`&&typeof t!=`bigint`)return null;let a=l(n),o=typeof t!=`number`&&typeof t!=`bigint`?e(t,{allowTrailingInvalid:a.allowTrailingInvalid,romanNumerals:a.romanNumerals,bigIntOnOverflow:!0,round:!1}):t;if(typeof o==`number`&&isNaN(o))return null;if(Number(o)===0)return a.zeroFormat;if(a.romanNumerals)return d(o);let c=typeof o==`bigint`?o<0n?-o:o:Math.abs(o),u=typeof c==`bigint`?c:Math.floor(c),f=`${u||``}`,p=typeof c==`bigint`?0:c-u;if(p===0)return`${o}`;let m=null,h=1/0;if(a.tolerance!==!1)for(let[e,t]of i){let n=Math.abs(p-e);if(n<a.tolerance||n===0){if(n===0){m=t;break}n<h&&(m=t,h=n)}}if(m){let e=s(m,a),t=e in r,n=f?a.separator??(t?``:` `):``;return`${o<0?`-`:``}${f}${n}${e}`}return`${o}`};export{n as defaultOptions,t as defaultTolerance,f as formatQuantity,d as formatRomanNumerals,i as fractionDecimalMatches,r as vulgarToAsciiMap};
2
2
  //# sourceMappingURL=format-quantity.production.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"format-quantity.production.mjs","names":[],"sources":["../src/constants.ts","../src/formatQuantity.ts"],"sourcesContent":["import type {\n ResolvedFormatQuantityOptions,\n SimpleFraction,\n Sixteenth,\n VulgarFraction,\n} from './types';\n\n/**\n * Default tolerance used by {@link formatQuantity} when determining if a number\n * is close enough to a fraction value to be considered equivalent.\n */\nexport const defaultTolerance = 0.0075 as const;\n\n/**\n * Default options for {@link formatQuantity}.\n */\nexport const defaultOptions: ResolvedFormatQuantityOptions = {\n vulgarFractions: false,\n tolerance: defaultTolerance,\n fractionSlash: false,\n romanNumerals: false,\n} as const;\n\n/**\n * Map of vulgar fractions to their traditional ASCII equivalents.\n */\nexport const vulgarToAsciiMap: Record<VulgarFraction, SimpleFraction> = {\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} as const;\n\n/**\n * Map of \"close enough\" decimal values to the {@link VulgarFraction} or\n * {@link Sixteenth} fraction string matches.\n */\nexport const fractionDecimalMatches: [number, VulgarFraction | Sixteenth][] = [\n [0.33, '⅓'],\n [0.66, '⅔'],\n [0.2, '⅕'],\n [0.4, '⅖'],\n [0.6, '⅗'],\n [0.8, '⅘'],\n [0.166, '⅙'],\n [0.833, '⅚'],\n [0.143, '⅐'],\n [0.111, '⅑'],\n [0.1, '⅒'],\n [0.125, '⅛'],\n [0.25, '¼'],\n [0.375, '⅜'],\n [0.5, '½'],\n [0.625, '⅝'],\n [0.75, '¾'],\n [0.875, '⅞'],\n [0.0625, '1/16'],\n [0.1875, '3/16'],\n [0.3125, '5/16'],\n [0.4375, '7/16'],\n [0.5625, '9/16'],\n [0.6875, '11/16'],\n [0.8125, '13/16'],\n [0.9375, '15/16'],\n] as const;\n","import { numericQuantity } from 'numeric-quantity';\nimport {\n defaultOptions,\n fractionDecimalMatches,\n vulgarToAsciiMap,\n} from './constants';\nimport type {\n FormatQuantity,\n FormatQuantityOptions,\n ResolvedFormatQuantityOptions,\n SimpleFraction,\n Sixteenth,\n VulgarFraction,\n} from './types';\n\n/**\n * Determines if two numbers are close enough to consider\n * them equal for the purposes of this package.\n */\nconst closeEnough = (n1: number, n2: number, tolerance: number) =>\n Math.abs(n1 - n2) < tolerance;\n\nconst superscriptDigits = '⁰¹²³⁴⁵⁶⁷⁸⁹';\nconst subscriptDigits = '₀₁₂₃₄₅₆₇₈₉';\n\nconst toSuperscript = (s: string) => {\n let r = '';\n for (let i = 0; i < s.length; i++) r += superscriptDigits[+s[i]];\n return r;\n};\nconst toSubscript = (s: string) => {\n let r = '';\n for (let i = 0; i < s.length; i++) r += subscriptDigits[+s[i]];\n return r;\n};\n\n/**\n * Applies the `vulgarFractions` or `fractionSlash` options as necessary.\n */\nconst getFraction = (\n vulgarFractionOrSixteenth: VulgarFraction | Sixteenth,\n { fractionSlash, vulgarFractions }: FormatQuantityOptions\n) => {\n if (vulgarFractions) {\n return vulgarFractionOrSixteenth;\n }\n\n const plainFraction: SimpleFraction =\n vulgarToAsciiMap[vulgarFractionOrSixteenth as VulgarFraction] ??\n vulgarFractionOrSixteenth;\n\n if (fractionSlash) {\n const [num, den] = plainFraction.split('/');\n return `${toSuperscript(num)}⁄${toSubscript(den)}`;\n }\n\n return plainFraction;\n};\n\n/**\n * Merges options object with default options, converting boolean to object if necessary.\n */\nconst normalizeOptions = (\n options: Parameters<FormatQuantity>[1]\n): ResolvedFormatQuantityOptions => ({\n ...defaultOptions,\n ...(typeof options === 'boolean' ? { vulgarFractions: options } : options),\n});\n\n// prettier-ignore\nconst romanNumeralValueKey = [\n \"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\",\n \"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\",\n \"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\",\n] as const;\n\n/**\n * Formats a number as Roman numerals. The number must be between\n * 1 and 3999, inclusive.\n */\nexport const formatRomanNumerals = (qty: number): string | null => {\n if (typeof qty !== 'number' || isNaN(qty)) {\n return null;\n }\n\n if (qty < 1 || qty >= 4000) {\n return '';\n }\n\n const floored = Math.floor(qty);\n\n const digits = `${floored}`.split('');\n let roman = '';\n let i = 3;\n while (i--) {\n roman = `${romanNumeralValueKey[+digits.pop()! + i * 10] || ''}${roman}`;\n }\n\n return `${Array(+digits.join('') + 1).join('M')}${roman}`;\n};\n\n/**\n * Formats a number (or string that appears to be a number)\n * as one would see it written in imperial measurements, e.g.\n * \"1 1/2\" instead of \"1.5\". To use vulgar fraction characters\n * like \"½\", pass `true` as the second argument. For other options\n * see {@link FormatQuantityOptions}.\n */\nexport const formatQuantity: FormatQuantity = (\n qty,\n options = defaultOptions\n) => {\n const qtyAsNumber =\n typeof qty === 'string'\n ? numericQuantity(qty, { round: false, allowTrailingInvalid: true })\n : qty;\n\n // Return `null` if input is not number-like.\n if (isNaN(qtyAsNumber) || qtyAsNumber === null) {\n return null;\n }\n\n // Return an empty string if the value is zero.\n // TODO: Consider a `zeroDisplay` option (e.g. `{ zeroDisplay: \"0\" }`) so\n // callers outside the recipe-ingredient use case can get \"0\" instead of \"\".\n if (qtyAsNumber === 0) {\n return '';\n }\n\n // The default options parameter in the function signature only takes effect\n // if the parameter is `undefined`. The nullish coalescing operator below\n // covers the `null` case.\n const opts = normalizeOptions(options ?? defaultOptions);\n\n if (opts.romanNumerals) {\n return formatRomanNumerals(qtyAsNumber);\n }\n\n const absoluteValue = Math.abs(qtyAsNumber);\n const flooredAbsVal = Math.floor(absoluteValue);\n const sign = qtyAsNumber < 0 ? '-' : '';\n const wholeStr = flooredAbsVal === 0 ? '' : `${flooredAbsVal}`;\n const decimalValue = absoluteValue - flooredAbsVal;\n\n // For integers just return the given value as a string.\n if (decimalValue === 0) {\n return `${qtyAsNumber}`;\n }\n\n for (const [num, vf] of fractionDecimalMatches) {\n if (closeEnough(decimalValue, num, opts.tolerance)) {\n const fraction = getFraction(vf, opts);\n const isVulgar = fraction in vulgarToAsciiMap;\n const sep = wholeStr\n ? (opts.separator ?? (isVulgar ? '' : ' '))\n : '';\n return `${sign}${wholeStr}${sep}${fraction}`;\n }\n }\n\n return `${qtyAsNumber}`;\n};\n"],"mappings":"mDAWA,MAAa,EAAmB,MAKnB,EAAgD,CAC3D,gBAAiB,GACjB,UAAW,EACX,cAAe,GACf,cAAe,GAChB,CAKY,EAA2D,CACtE,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACN,CAMY,EAAiE,CAC5E,CAAC,IAAM,IAAI,CACX,CAAC,IAAM,IAAI,CAC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B,sGAI5B,CAMY,EAAuB,GAA+B,CACjE,GAAI,OAAO,GAAQ,UAAY,MAAM,EAAI,CACvC,OAAO,KAGT,GAAI,EAAM,GAAK,GAAO,IACpB,MAAO,GAKT,IAAM,EAAS,GAFC,KAAK,MAAM,EAAI,GAEH,MAAM,GAAG,CACjC,EAAQ,GACR,EAAI,EACR,KAAO,KACL,EAAQ,GAAG,EAAqB,CAAC,EAAO,KAAK,CAAI,EAAI,KAAO,KAAK,IAGnE,MAAO,GAAG,MAAM,CAAC,EAAO,KAAK,GAAG,CAAG,EAAE,CAAC,KAAK,IAAI,GAAG,KAUvC,GACX,EACA,EAAU,IACP,CACH,IAAM,EACJ,OAAO,GAAQ,SACX,EAAgB,EAAK,CAAE,MAAO,GAAO,qBAAsB,GAAM,CAAC,CAClE,EAGN,GAAI,MAAM,EAAY,EAAI,IAAgB,KACxC,OAAO,KAMT,GAAI,IAAgB,EAClB,MAAO,GAMT,IAAM,EAAO,EAAiB,GAAW,EAAe,CAExD,GAAI,EAAK,cACP,OAAO,EAAoB,EAAY,CAGzC,IAAM,EAAgB,KAAK,IAAI,EAAY,CACrC,EAAgB,KAAK,MAAM,EAAc,CACzC,EAAO,EAAc,EAAI,IAAM,GAC/B,EAAW,IAAkB,EAAI,GAAK,GAAG,IACzC,EAAe,EAAgB,EAGrC,GAAI,IAAiB,EACnB,MAAO,GAAG,IAGZ,IAAK,GAAM,CAAC,EAAK,KAAO,EACtB,GAAI,EAAY,EAAc,EAAK,EAAK,UAAU,CAAE,CAClD,IAAM,EAAW,EAAY,EAAI,EAAK,CAChC,EAAW,KAAY,EAI7B,MAAO,GAAG,IAAO,IAHL,EACP,EAAK,YAAc,EAAW,GAAK,KACpC,KAC8B,IAItC,MAAO,GAAG"}
1
+ {"version":3,"file":"format-quantity.production.mjs","names":[],"sources":["../src/constants.ts","../src/formatQuantity.ts"],"sourcesContent":["import type {\n ResolvedFormatQuantityOptions,\n SimpleFraction,\n Sixteenth,\n VulgarFraction,\n} from './types';\n\n/**\n * Default tolerance used by {@link formatQuantity} when determining if a number\n * is close enough to a fraction value to be considered equivalent.\n */\nexport const defaultTolerance = 0.0075 as const;\n\n/**\n * Default options for {@link formatQuantity}.\n */\nexport const defaultOptions: Readonly<ResolvedFormatQuantityOptions> = Object.freeze({\n vulgarFractions: false,\n tolerance: defaultTolerance,\n fractionSlash: false,\n romanNumerals: false,\n zeroFormat: '',\n allowTrailingInvalid: true,\n});\n\n/**\n * Map of vulgar fractions to their traditional ASCII equivalents.\n */\nexport const vulgarToAsciiMap: Readonly<Record<VulgarFraction, SimpleFraction>> = Object.freeze({\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});\n\n/**\n * Map of \"close enough\" values to the {@link VulgarFraction} or {@link Sixteenth} fraction\n * string matches. The value +/- the `tolerance` option (or {@link defaultTolerance} if not\n * specified) is considered close enough to match the fraction.\n */\nexport const fractionDecimalMatches: readonly (readonly [number, VulgarFraction | Sixteenth])[] =\n Object.freeze(\n (\n [\n [1 / 16, '1/16'],\n [1 / 10, '⅒'],\n [1 / 9, '⅑'],\n [1 / 8, '⅛'],\n [1 / 7, '⅐'],\n [1 / 6, '⅙'],\n [3 / 16, '3/16'],\n [1 / 5, '⅕'],\n [1 / 4, '¼'],\n [5 / 16, '5/16'],\n [1 / 3, '⅓'],\n [3 / 8, '⅜'],\n [2 / 5, '⅖'],\n [7 / 16, '7/16'],\n [1 / 2, '½'],\n [9 / 16, '9/16'],\n [3 / 5, '⅗'],\n [5 / 8, '⅝'],\n [2 / 3, '⅔'],\n [11 / 16, '11/16'],\n [3 / 4, '¾'],\n [4 / 5, '⅘'],\n [13 / 16, '13/16'],\n [5 / 6, '⅚'],\n [7 / 8, '⅞'],\n [15 / 16, '15/16'],\n ] satisfies [number, VulgarFraction | Sixteenth][]\n ).map(entry => Object.freeze(entry))\n );\n","import { numericQuantity } from 'numeric-quantity';\nimport { defaultOptions, fractionDecimalMatches, vulgarToAsciiMap } from './constants';\nimport type {\n FormatQuantity,\n ResolvedFormatQuantityOptions,\n SimpleFraction,\n Sixteenth,\n VulgarFraction,\n} from './types';\n\nconst superscriptDigits = '⁰¹²³⁴⁵⁶⁷⁸⁹';\nconst subscriptDigits = '₀₁₂₃₄₅₆₇₈₉';\n\n// oxlint-disable-next-line typescript/no-misused-spread\nconst toSuperscript = (s: string) => [...s].map(c => superscriptDigits[+c]).join('');\n// oxlint-disable-next-line typescript/no-misused-spread\nconst toSubscript = (s: string) => [...s].map(c => subscriptDigits[+c]).join('');\n\n/**\n * Applies the `vulgarFractions` or `fractionSlash` options as necessary.\n */\nconst getFraction = (\n vulgarFractionOrSixteenth: VulgarFraction | Sixteenth,\n { fractionSlash, vulgarFractions }: ResolvedFormatQuantityOptions\n) => {\n if (vulgarFractions) {\n return vulgarFractionOrSixteenth;\n }\n\n const plainFraction: SimpleFraction =\n vulgarToAsciiMap[vulgarFractionOrSixteenth as VulgarFraction] ?? vulgarFractionOrSixteenth;\n\n if (fractionSlash) {\n const [num, den] = plainFraction.split('/');\n return `${toSuperscript(num)}⁄${toSubscript(den)}`;\n }\n\n return plainFraction;\n};\n\n/**\n * Only `false` (matching disabled) or a non-negative number is a valid\n * `tolerance`. Everything else—negative numbers, `NaN`, non-numbers,\n * `null`, `undefined`—resolves to {@link defaultTolerance}.\n */\nconst isValidTolerance = (tolerance: unknown): tolerance is number | false =>\n tolerance === false || (typeof tolerance === 'number' && tolerance >= 0);\n\n/**\n * Merges options object with default options, converting boolean to object if necessary.\n */\nconst normalizeOptions = (\n options: Parameters<FormatQuantity>[1]\n): ResolvedFormatQuantityOptions => {\n const opts: ResolvedFormatQuantityOptions = {\n ...defaultOptions,\n ...(typeof options === 'boolean'\n ? { vulgarFractions: options }\n : typeof options === 'object' && options !== null\n ? options\n : {}),\n };\n\n if (!isValidTolerance(opts.tolerance)) {\n opts.tolerance = defaultOptions.tolerance;\n }\n\n if (typeof opts.zeroFormat !== 'string') {\n opts.zeroFormat = defaultOptions.zeroFormat;\n }\n\n if (opts.allowTrailingInvalid !== false) {\n opts.allowTrailingInvalid = true;\n }\n\n return opts;\n};\n\n// oxfmt-ignore\nconst romanNumeralsByPlace = [\n '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',\n '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',\n '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX',\n] as const;\n\n/**\n * Formats a number or bigint as Roman numerals. The number must be between\n * 1 and 3999, inclusive; any other value—including non-numbers,\n * `NaN`, and non-finite numbers—yields `null`.\n */\nexport const formatRomanNumerals = (quantity: number | bigint): string | null => {\n if (\n (typeof quantity !== 'number' && typeof quantity !== 'bigint') ||\n !(quantity >= 1 && quantity < 4000)\n ) {\n return null;\n }\n\n const qty = Number(quantity);\n\n const floored = Math.floor(qty);\n\n const digits = `${floored}`.split('');\n let roman = '';\n let i = 3;\n while (i--) {\n roman = `${romanNumeralsByPlace[+digits.pop()! + i * 10] || ''}${roman}`;\n }\n\n return `${Array(+digits.join('') + 1).join('M')}${roman}`;\n};\n\n/**\n * Formats a number (or string that appears to be a number)\n * as one would see it written in imperial measurements, e.g.\n * \"1 1/2\" instead of \"1.5\". To use vulgar fraction characters\n * like \"½\", pass `true` as the second argument. For other options\n * see {@link FormatQuantityOptions}.\n */\nexport const formatQuantity: FormatQuantity = (qty, options) => {\n // Only numbers, bigints, and strings are accepted. Anything else (objects, booleans,\n // nullish, arrays like `[1]` that would coerce to a numeric string) is\n // rejected up front so off-type inputs behave consistently.\n if (typeof qty !== 'number' && typeof qty !== 'string' && typeof qty !== 'bigint') {\n return null;\n }\n\n const opts = normalizeOptions(options);\n\n const qtyAsNumber =\n typeof qty !== 'number' && typeof qty !== 'bigint'\n ? numericQuantity(qty, {\n allowTrailingInvalid: opts.allowTrailingInvalid,\n romanNumerals: opts.romanNumerals,\n bigIntOnOverflow: true,\n round: false,\n })\n : qty;\n\n // Return `null` if input is not number-like.\n if (typeof qtyAsNumber === 'number' && isNaN(qtyAsNumber)) {\n return null;\n }\n\n // Return empty string (or configured `zeroFormat`) if the value is zero.\n if (Number(qtyAsNumber) === 0) {\n return opts.zeroFormat;\n }\n\n if (opts.romanNumerals) {\n return formatRomanNumerals(qtyAsNumber);\n }\n\n const absoluteValue =\n typeof qtyAsNumber === 'bigint'\n ? qtyAsNumber < 0n\n ? -qtyAsNumber\n : qtyAsNumber\n : Math.abs(qtyAsNumber);\n const flooredAbsVal =\n typeof absoluteValue === 'bigint' ? absoluteValue : Math.floor(absoluteValue);\n const wholeNumberStr = `${flooredAbsVal || ''}`;\n const decimalValue =\n typeof absoluteValue === 'bigint' ? 0 : absoluteValue - (flooredAbsVal as number);\n\n // For integers just return the given value as a string.\n if (decimalValue === 0) {\n return `${qtyAsNumber}`;\n }\n\n let closestMatch: VulgarFraction | Sixteenth | null = null;\n let closestMatchDiff = Infinity;\n // `tolerance: false` disables fraction matching entirely.\n if (opts.tolerance !== false) {\n for (const [num, vf] of fractionDecimalMatches) {\n const diff = Math.abs(decimalValue - num);\n // `diff === 0` keeps exact quotients matching even at `tolerance: 0`.\n if (diff < opts.tolerance || diff === 0) {\n if (diff === 0) {\n closestMatch = vf;\n break;\n }\n if (diff < closestMatchDiff) {\n closestMatch = vf;\n closestMatchDiff = diff;\n }\n }\n }\n }\n\n if (closestMatch) {\n const fraction = getFraction(closestMatch, opts);\n const isVulgar = fraction in vulgarToAsciiMap;\n const sep = wholeNumberStr ? (opts.separator ?? (isVulgar ? '' : ' ')) : '';\n return `${qtyAsNumber < 0 ? '-' : ''}${wholeNumberStr}${sep}${fra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?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.FormatQuantity={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=.0075,n=Object.freeze({vulgarFractions:!1,tolerance:t,fractionSlash:!1,romanNumerals:!1,zeroFormat:``,allowTrailingInvalid:!0}),r=Object.freeze({"¼":`1/4`,"½":`1/2`,"¾":`3/4`,"⅐":`1/7`,"⅑":`1/9`,"⅒":`1/10`,"⅓":`1/3`,"⅔":`2/3`,"⅕":`1/5`,"⅖":`2/5`,"⅗":`3/5`,"⅘":`4/5`,"⅙":`1/6`,"⅚":`5/6`,"⅛":`1/8`,"⅜":`3/8`,"⅝":`5/8`,"⅞":`7/8`}),i=Object.freeze([[1/16,`1/16`],[1/10,`⅒`],[1/9,`⅑`],[1/8,`⅛`],[1/7,`⅐`],[1/6,`⅙`],[3/16,`3/16`],[1/5,`⅕`],[1/4,`¼`],[5/16,`5/16`],[1/3,`⅓`],[3/8,`⅜`],[2/5,`⅖`],[7/16,`7/16`],[1/2,`½`],[9/16,`9/16`],[3/5,`⅗`],[5/8,`⅝`],[2/3,`⅔`],[11/16,`11/16`],[3/4,`¾`],[4/5,`⅘`],[13/16,`13/16`],[5/6,`⅚`],[7/8,`⅞`],[15/16,`15/16`]].map(e=>Object.freeze(e))),a=[48,1632,1776,1984,2406,2534,2662,2790,2918,3046,3174,3302,3430,3558,3664,3792,3872,4160,4240,6112,6160,6470,6608,6784,6800,6992,7088,7232,7248,42528,43216,43264,43472,43504,43600,44016,65296,66720,68912,68928,69734,69872,69942,70096,70384,70736,70864,71248,71360,71376,71386,71472,71904,72016,72688,72784,73040,73120,73184,73552,90416,92768,92864,93008,93552,118e3,120782,120792,120802,120812,120822,123200,123632,124144,124401,125264,130032],o=e=>e.replace(/\p{Nd}/gu,e=>{let t=e.codePointAt(0);if(t<=57)return e;let n=0,r=a.length-1;for(;n<r;){let e=n+r+1>>>1;a[e]<=t?n=e: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L`,Ⅽ:`C`,Ⅾ:`D`,Ⅿ:`M`,ⅰ:`I`,ⅱ:`II`,ⅲ:`III`,ⅳ:`IV`,ⅴ:`V`,ⅵ:`VI`,ⅶ:`VII`,ⅷ:`VIII`,ⅸ:`IX`,ⅹ:`X`,ⅺ:`XI`,ⅻ:`XII`,ⅼ:`L`,ⅽ:`C`,ⅾ:`D`,ⅿ:`M`},m=/([ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿ])/gi,h=/^(?=[MDCLXVI])(M{0,3})(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$/i,g={round:3,allowTrailingInvalid:!1,romanNumerals:!1,bigIntOnOverflow:!1,decimalSeparator:`.`,allowCurrency:!1,percentage:!1,verbose:!1},_=e=>{let t=e.replace(m,(e,t)=>p[t]).toUpperCase(),n=h.exec(t);if(!n)return NaN;let[,r,i,a,o]=n;return(f[r]??0)+(f[i]??0)+(f[a]??0)+(f[o]??0)},v=/^\s*\//,y=/^([-+]?)\s*(\p{Sc}+)\s*/u,b=/\s*(\p{Sc}+)\s*$/u,x=/\s*%$/,S=BigInt(2**53-1),C=e=>10n**BigInt(e),w=(e,t,n)=>{let r,i=1n;if(!t)r=BigInt(e);else if(t.startsWith(`.`)||t.startsWith(`e`)||t.startsWith(`E`)){let n=t.search(/[eE]/),a=n===-1?0:parseInt(t.slice(n+1));if(!Number.isFinite(a)||Math.abs(a)>1e4)return;let o=(n===-1?t:t.slice(0,n)).slice(1);r=BigInt(`${e}${o}`),o&&(i=C(o.length)),a>0?r*=C(a):a<0&&(i*=C(-a))}else if(v.test(t))r=BigInt(e),i=BigInt(t.replace(`/`,``).trim());else{let[n,a]=t.split(`/`);i=BigInt(a.trim()),r=BigInt(e)*i+BigInt(n.trim())}if(n&&(i*=100n),i===0n)return;let a=(2n*r+i)/(2n*i);return a>S?a:void 0};function T(e,t=g){let n={...g,...t},r;if(typeof e==`string`)r=e;else try{r=String(e)}catch{r=``}let i,a,f,p,m,h,S,C,T=e=>{let t={value:e,input:r};return i&&(t.currencyPrefix=i),a&&(t.currencySuffix=a),f&&(t.percentageSuffix=f),p&&(t.trailingInvalid=p),m&&(t.sign=m),h!==void 0&&(t.whole=h),S!==void 0&&(t.numerator=S),C!==void 0&&(t.denominator=C),t},E=e=>n.verbose?T(e):e,D=e=>f&&n.percentage!==`number`?e/100:e;if(typeof e==`symbol`)return E(NaN);if(typeof e==`number`||typeof e==`bigint`)return E(e);let O=NaN,k=r,A=!0;for(;A;){if(A=!1,n.allowCurrency){let e=y.exec(k);e?.[2]&&(i=(i??``)+e[2],k=(e[1]||``)+k.slice(e[0].length),A=!0);let t=b.exec(k);t&&(a=t[1]+(a??``),k=k.slice(0,-t[0].length),A=!0)}if(!f&&n.percentage){let e=x.exec(k);e&&(f=!0,k=k.slice(0,-e[0].length),A=!0)}}let j=o(k.replace(d,(e,t)=>` ${l[t]}`).replace(c,e=>s[e]).replace(`⁄`,`/`).trim());if(j.length===0)return E(NaN);let M=j;if(n.decimalSeparator===`,`){let e=(j.match(/,/g)||[]).length;if(e===1)M=j.replaceAll(`.`,`_`).replace(`,`,`.`);else if(e>1){let e=j.indexOf(`,`),t=j.indexOf(`,`,e+1);M=j.substring(0,t).replaceAll(`.`,`_`).replace(`,`,`.`)}else M=j.replaceAll(`.`,`_`)}let N=u.exec(M);if(!N)return n.romanNumerals?E(D(_(j))):E(NaN);let P=N[0].length-(N[7]?.length??0),F=j.slice(P).trim();if(F&&(p=F,!n.allowTrailingInvalid))return E(NaN);let[,I,L,R]=N;(I===`-`||I===`+`)&&(m=I);let z=L.replaceAll(`,`,``).replaceAll(`_`,``),B=R?.replaceAll(`,`,``).replaceAll(`_`,``);if(n.bigIntOnOverflow){let e=w(z,B,!!f&&n.percentage!==`number`);if(e!==void 0)return E(I===`-`?-e:e)}if(O=!z&&B&&B.startsWith(`.`)?0:parseInt(z),!B)return O=I===`-`?O*-1:O,E(D(O));let V=typeof n.round==`number`&&Number.isFinite(n.round)?Math.floor(Math.max(0,n.round)):!1,H=V===!1?NaN:10**V,U=Number.isFinite(H)?H:NaN,W=(e,t)=>{let n=Math.round(t)/U;return Number.isFinite(n)||!Number.isFinite(e)?n:e};if(B.startsWith(`.`)||B.startsWith(`e`)||B.startsWith(`E`)){let e=parseFloat(`${O}${B}`);O=isNaN(U)?e:W(e,e*U)}else if(v.test(B)){let e=parseInt(z),t=parseInt(B.replace(`/`,``));S=e,C=t,O=isNaN(U)?e/t:W(e/t,e*U/t)}else{let[e,t]=B.split(`/`).map(e=>parseInt(e));h=O,S=e,C=t,O+=isNaN(U)?e/t:W(e/t,e*U/t)}return O=I===`-`?O*-1:O,E(D(O))}let E=e=>[...e].map(e=>`⁰¹²³⁴⁵⁶⁷⁸⁹`[+e]).join(``),D=e=>[...e].map(e=>`₀₁₂₃₄₅₆₇₈₉`[+e]).join(``),O=(e,{fractionSlash:t,vulgarFractions:n})=>{if(n)return e;let i=r[e]??e;if(t){let[e,t]=i.split(`/`);return`${E(e)}⁄${D(t)}`}return i},k=e=>e===!1||typeof e==`number`&&e>=0,A=e=>{let t={...n,...typeof e==`boolean`?{vulgarFractions:e}:typeof e==`object`&&e?e:{}};return k(t.tolerance)||(t.tolerance=n.tolerance),typeof t.zeroFormat!=`string`&&(t.zeroFormat=n.zeroFormat),t.allowTrailingInvalid!==!1&&(t.allowTrailingInvalid=!0),t},j=`.C.CC.CCC.CD.D.DC.DCC.DCCC.CM..X.XX.XXX.XL.L.LX.LXX.LXXX.XC..I.II.III.IV.V.VI.VII.VIII.IX`.split(`.`),M=e=>{if(typeof e!=`number`&&typeof e!=`bigint`||!(e>=1&&e<4e3))return null;let t=Number(e),n=`${Math.floor(t)}`.split(``),r=``,i=3;for(;i--;)r=`${j[+n.pop()+i*10]||``}${r}`;return`${Array(+n.join(``)+1).join(`M`)}${r}`};e.defaultOptions=n,e.defaultTolerance=t,e.formatQuantity=(e,t)=>{if(typeof e!=`number`&&typeof e!=`string`&&typeof e!=`bigint`)return null;let n=A(t),a=typeof e!=`number`&&typeof e!=`bigint`?T(e,{allowTrailingInvalid:n.allowTrailingInvalid,romanNumerals:n.romanNumerals,bigIntOnOverflow:!0,round:!1}):e;if(typeof a==`number`&&isNaN(a))return null;if(Number(a)===0)return n.zeroFormat;if(n.romanNumerals)return M(a);let o=typeof a==`bigint`?a<0n?-a:a:Math.abs(a),s=typeof o==`bigint`?o:Math.floor(o),c=`${s||``}`,l=typeof o==`bigint`?0:o-s;if(l===0)return`${a}`;let u=null,d=1/0;if(n.tolerance!==!1)for(let[e,t]of i){let r=Math.abs(l-e);if(r<n.tolerance||r===0){if(r===0){u=t;break}r<d&&(u=t,d=r)}}if(u){let e=O(u,n),t=e in r,i=c?n.separator??(t?``:` `):``;return`${a<0?`-`:``}${c}${i}${e}`}return`${a}`},e.formatRomanNumerals=M,e.fractionDecimalMatches=i,e.vulgarToAsciiMap=r});
2
+ typeof window<"u"&&typeof exports=="object"&&(window.FormatQuantity=exports);
3
+ //# sourceMappingURL=format-quantity.umd.min.js.map