format-quantity 3.0.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,157 +1,208 @@
1
- // src/constants.ts
2
- var defaultTolerance = 75e-4;
3
- var defaultOptions = {
4
- vulgarFractions: false,
5
- tolerance: defaultTolerance,
6
- fractionSlash: false,
7
- romanNumerals: false
8
- };
9
- var vulgarToAsciiMap = {
10
- "\xBC": "1/4",
11
- "\xBD": "1/2",
12
- "\xBE": "3/4",
13
- "\u2150": "1/7",
14
- "\u2151": "1/9",
15
- "\u2152": "1/10",
16
- "\u2153": "1/3",
17
- "\u2154": "2/3",
18
- "\u2155": "1/5",
19
- "\u2156": "2/5",
20
- "\u2157": "3/5",
21
- "\u2158": "4/5",
22
- "\u2159": "1/6",
23
- "\u215A": "5/6",
24
- "\u215B": "1/8",
25
- "\u215C": "3/8",
26
- "\u215D": "5/8",
27
- "\u215E": "7/8"
1
+ import { numericQuantity } from "numeric-quantity";
2
+ //#region src/constants.ts
3
+ /**
4
+ * Default tolerance used by {@link formatQuantity} when determining if a number
5
+ * is close enough to a fraction value to be considered equivalent.
6
+ */
7
+ const defaultTolerance = .0075;
8
+ /**
9
+ * Default options for {@link formatQuantity}.
10
+ */
11
+ const defaultOptions = Object.freeze({
12
+ vulgarFractions: false,
13
+ tolerance: defaultTolerance,
14
+ fractionSlash: false,
15
+ romanNumerals: false,
16
+ zeroFormat: "",
17
+ allowTrailingInvalid: true
18
+ });
19
+ /**
20
+ * Map of vulgar fractions to their traditional ASCII equivalents.
21
+ */
22
+ const vulgarToAsciiMap = Object.freeze({
23
+ "¼": "1/4",
24
+ "½": "1/2",
25
+ "¾": "3/4",
26
+ "": "1/7",
27
+ "": "1/9",
28
+ "⅒": "1/10",
29
+ "⅓": "1/3",
30
+ "⅔": "2/3",
31
+ "⅕": "1/5",
32
+ "⅖": "2/5",
33
+ "⅗": "3/5",
34
+ "⅘": "4/5",
35
+ "⅙": "1/6",
36
+ "⅚": "5/6",
37
+ "⅛": "1/8",
38
+ "⅜": "3/8",
39
+ "⅝": "5/8",
40
+ "⅞": "7/8"
41
+ });
42
+ /**
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.
46
+ */
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)));
75
+ //#endregion
76
+ //#region src/formatQuantity.ts
77
+ const superscriptDigits = "⁰¹²³⁴⁵⁶⁷⁸⁹";
78
+ const subscriptDigits = "₀₁₂₃₄₅₆₇₈₉";
79
+ const toSuperscript = (s) => [...s].map((c) => superscriptDigits[+c]).join("");
80
+ const toSubscript = (s) => [...s].map((c) => subscriptDigits[+c]).join("");
81
+ /**
82
+ * Applies the `vulgarFractions` or `fractionSlash` options as necessary.
83
+ */
84
+ const getFraction = (vulgarFractionOrSixteenth, { fractionSlash, vulgarFractions }) => {
85
+ if (vulgarFractions) return vulgarFractionOrSixteenth;
86
+ const plainFraction = vulgarToAsciiMap[vulgarFractionOrSixteenth] ?? vulgarFractionOrSixteenth;
87
+ if (fractionSlash) {
88
+ const [num, den] = plainFraction.split("/");
89
+ return `${toSuperscript(num)}⁄${toSubscript(den)}`;
90
+ }
91
+ return plainFraction;
28
92
  };
29
- var fractionDecimalMatches = [
30
- [0.33, "\u2153"],
31
- [0.66, "\u2154"],
32
- [0.2, "\u2155"],
33
- [0.4, "\u2156"],
34
- [0.6, "\u2157"],
35
- [0.8, "\u2158"],
36
- [0.166, "\u2159"],
37
- [0.833, "\u215A"],
38
- [0.143, "\u2150"],
39
- [0.111, "\u2151"],
40
- [0.1, "\u2152"],
41
- [0.125, "\u215B"],
42
- [0.25, "\xBC"],
43
- [0.375, "\u215C"],
44
- [0.5, "\xBD"],
45
- [0.625, "\u215D"],
46
- [0.75, "\xBE"],
47
- [0.875, "\u215E"],
48
- [0.0625, "1/16"],
49
- [0.1875, "3/16"],
50
- [0.3125, "5/16"],
51
- [0.4375, "7/16"],
52
- [0.5625, "9/16"],
53
- [0.6875, "11/16"],
54
- [0.8125, "13/16"],
55
- [0.9375, "15/16"]
56
- ];
57
-
58
- // src/formatQuantity.ts
59
- var closeEnough = (n1, n2, tolerance) => Math.abs(n1 - n2) < tolerance;
60
- var getFraction = (vulgarFractionOrSixteenth, { fractionSlash, vulgarFractions }) => {
61
- if (vulgarFractions) {
62
- return vulgarFractionOrSixteenth;
63
- }
64
- const plainFraction = vulgarToAsciiMap[vulgarFractionOrSixteenth] ?? vulgarFractionOrSixteenth;
65
- if (fractionSlash) {
66
- return plainFraction.replace("/", "\u2044");
67
- }
68
- return plainFraction;
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
+ /**
100
+ * Merges options object with default options, converting boolean to object if necessary.
101
+ */
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;
69
111
  };
70
- var normalizeOptions = (options) => ({
71
- ...defaultOptions,
72
- ...typeof options === "boolean" ? { vulgarFractions: options } : options
73
- });
74
- var romanNumeralValueKey = [
75
- "",
76
- "C",
77
- "CC",
78
- "CCC",
79
- "CD",
80
- "D",
81
- "DC",
82
- "DCC",
83
- "DCCC",
84
- "CM",
85
- "",
86
- "X",
87
- "XX",
88
- "XXX",
89
- "XL",
90
- "L",
91
- "LX",
92
- "LXX",
93
- "LXXX",
94
- "XC",
95
- "",
96
- "I",
97
- "II",
98
- "III",
99
- "IV",
100
- "V",
101
- "VI",
102
- "VII",
103
- "VIII",
104
- "IX"
112
+ const romanNumeralsByPlace = [
113
+ "",
114
+ "C",
115
+ "CC",
116
+ "CCC",
117
+ "CD",
118
+ "D",
119
+ "DC",
120
+ "DCC",
121
+ "DCCC",
122
+ "CM",
123
+ "",
124
+ "X",
125
+ "XX",
126
+ "XXX",
127
+ "XL",
128
+ "L",
129
+ "LX",
130
+ "LXX",
131
+ "LXXX",
132
+ "XC",
133
+ "",
134
+ "I",
135
+ "II",
136
+ "III",
137
+ "IV",
138
+ "V",
139
+ "VI",
140
+ "VII",
141
+ "VIII",
142
+ "IX"
105
143
  ];
106
- var formatRomanNumerals = (qty) => {
107
- if (typeof qty !== "number" || isNaN(qty)) {
108
- return null;
109
- }
110
- if (qty < 1 || qty >= 4e3) {
111
- return "";
112
- }
113
- const floored = Math.floor(qty);
114
- const digits = `${floored}`.split("");
115
- let roman = "";
116
- let i = 3;
117
- while (i--) {
118
- roman = `${romanNumeralValueKey[+digits.pop() + i * 10] || ""}${roman}`;
119
- }
120
- return `${Array(+digits.join("") + 1).join("M")}${roman}`;
144
+ /**
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`.
148
+ */
149
+ const formatRomanNumerals = (quantity) => {
150
+ if (typeof quantity !== "number" && typeof quantity !== "bigint" || !(quantity >= 1 && quantity < 4e3)) return null;
151
+ const qty = Number(quantity);
152
+ const digits = `${Math.floor(qty)}`.split("");
153
+ let roman = "";
154
+ let i = 3;
155
+ while (i--) roman = `${romanNumeralsByPlace[+digits.pop() + i * 10] || ""}${roman}`;
156
+ return `${Array(+digits.join("") + 1).join("M")}${roman}`;
121
157
  };
122
- var formatQuantity = (qty, options = defaultOptions) => {
123
- const qtyAsNumber = typeof qty === "string" ? parseFloat(qty) : qty;
124
- if (isNaN(qtyAsNumber) || qtyAsNumber === null) {
125
- return null;
126
- }
127
- if (qtyAsNumber === 0) {
128
- return "";
129
- }
130
- const opts = normalizeOptions(options ?? defaultOptions);
131
- if (opts.romanNumerals) {
132
- return formatRomanNumerals(qtyAsNumber);
133
- }
134
- const absoluteValue = Math.abs(qtyAsNumber);
135
- const flooredAbsVal = Math.floor(absoluteValue);
136
- const flooredAbsValStr = `${qtyAsNumber < 0 ? "-" : ""}${flooredAbsVal === 0 ? "" : `${flooredAbsVal} `}`;
137
- const decimalValue = absoluteValue - flooredAbsVal;
138
- if (decimalValue === 0) {
139
- return `${qtyAsNumber}`;
140
- }
141
- for (const [num, vf] of fractionDecimalMatches) {
142
- if (closeEnough(decimalValue, num, opts.tolerance)) {
143
- const fraction = getFraction(vf, opts);
144
- const int = fraction in vulgarToAsciiMap ? flooredAbsValStr.trim() : flooredAbsValStr;
145
- return `${int}${fraction}`;
146
- }
147
- }
148
- return `${qtyAsNumber}`;
149
- };
150
- export {
151
- defaultOptions,
152
- defaultTolerance,
153
- formatQuantity,
154
- fractionDecimalMatches,
155
- vulgarToAsciiMap
158
+ /**
159
+ * Formats a number (or string that appears to be a number)
160
+ * as one would see it written in imperial measurements, e.g.
161
+ * "1 1/2" instead of "1.5". To use vulgar fraction characters
162
+ * like "½", pass `true` as the second argument. For other options
163
+ * see {@link FormatQuantityOptions}.
164
+ */
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
173
+ }) : qty;
174
+ if (typeof qtyAsNumber === "number" && isNaN(qtyAsNumber)) return null;
175
+ if (Number(qtyAsNumber) === 0) return opts.zeroFormat;
176
+ if (opts.romanNumerals) return formatRomanNumerals(qtyAsNumber);
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;
181
+ if (decimalValue === 0) return `${qtyAsNumber}`;
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);
199
+ const isVulgar = fraction in vulgarToAsciiMap;
200
+ const sep = wholeNumberStr ? opts.separator ?? (isVulgar ? "" : " ") : "";
201
+ return `${qtyAsNumber < 0 ? "-" : ""}${wholeNumberStr}${sep}${fraction}`;
202
+ }
203
+ return `${qtyAsNumber}`;
156
204
  };
205
+ //#endregion
206
+ export { defaultOptions, defaultTolerance, formatQuantity, formatRomanNumerals, fractionDecimalMatches, vulgarToAsciiMap };
207
+
157
208
  //# sourceMappingURL=format-quantity.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constants.ts","../src/formatQuantity.ts"],"sourcesContent":["import type {\n FormatQuantityOptions,\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 = {\n vulgarFractions: false,\n tolerance: defaultTolerance,\n fractionSlash: false,\n romanNumerals: false,\n} as const satisfies Required<FormatQuantityOptions>;\n\n/**\n * Map of vulgar fractions to their traditional ASCII equivalents.\n */\nexport const vulgarToAsciiMap = {\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 satisfies Record<VulgarFraction, SimpleFraction>;\n\n/**\n * Map of \"close enough\" decimal values to the {@link VulgarFraction} or\n * {@link Sixteenth} fraction string matches.\n */\nexport const fractionDecimalMatches = [\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] satisfies [number, VulgarFraction | Sixteenth][];\n","import {\n defaultOptions,\n fractionDecimalMatches,\n vulgarToAsciiMap,\n} from './constants';\nimport type {\n FormatQuantity,\n FormatQuantityOptions,\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\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 return plainFraction.replace('/', '⁄');\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): Required<FormatQuantityOptions> => ({\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) => {\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 // TODO: use numericQuantity instead of parseFloat?\n const qtyAsNumber = typeof qty === 'string' ? parseFloat(qty) : 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 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 flooredAbsValStr = `${qtyAsNumber < 0 ? '-' : ''}${\n flooredAbsVal === 0 ? '' : `${flooredAbsVal} `\n }`;\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 int =\n fraction in vulgarToAsciiMap\n ? flooredAbsValStr.trim()\n : flooredAbsValStr;\n return `${int}${fraction}`;\n }\n }\n\n return `${qtyAsNumber}`;\n};\n"],"mappings":";AAWO,IAAM,mBAAmB;AAKzB,IAAM,iBAAiB;AAAA,EAC5B,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,eAAe;AACjB;AAKO,IAAM,mBAAmB;AAAA,EAC9B,QAAK;AAAA,EACL,QAAK;AAAA,EACL,QAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AAAA,EACL,UAAK;AACP;AAMO,IAAM,yBAAyB;AAAA,EACpC,CAAC,MAAM,QAAG;AAAA,EACV,CAAC,MAAM,QAAG;AAAA,EACV,CAAC,KAAK,QAAG;AAAA,EACT,CAAC,KAAK,QAAG;AAAA,EACT,CAAC,KAAK,QAAG;AAAA,EACT,CAAC,KAAK,QAAG;AAAA,EACT,CAAC,OAAO,QAAG;AAAA,EACX,CAAC,OAAO,QAAG;AAAA,EACX,CAAC,OAAO,QAAG;AAAA,EACX,CAAC,OAAO,QAAG;AAAA,EACX,CAAC,KAAK,QAAG;AAAA,EACT,CAAC,OAAO,QAAG;AAAA,EACX,CAAC,MAAM,MAAG;AAAA,EACV,CAAC,OAAO,QAAG;AAAA,EACX,CAAC,KAAK,MAAG;AAAA,EACT,CAAC,OAAO,QAAG;AAAA,EACX,CAAC,MAAM,MAAG;AAAA,EACV,CAAC,OAAO,QAAG;AAAA,EACX,CAAC,QAAQ,MAAM;AAAA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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,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;AACP,CAAC;;;;;;AAOD,MAAa,yBACX,OAAO,OAEH;CACE,CAAC,IAAI,IAAI,MAAM;CACf,CAAC,IAAI,IAAI,GAAG;CACZ,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,IAAI,MAAM;CACf,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,IAAI,MAAM;CACf,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,IAAI,MAAM;CACf,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,IAAI,MAAM;CACf,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,KAAK,IAAI,OAAO;CACjB,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,IAAI,GAAG,GAAG;CACX,CAAC,KAAK,IAAI,OAAO;CACjB,CAA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I,eAAkD;CACtD,IAAI,mBAAmB;CAEvB,IAAI,KAAK,cAAc,OACrB,KAAK,MAAM,CAAC,KAAK,OAAO,wBAAwB;EAC9C,MAAM,OAAO,KAAK,IAAI,eAAe,GAAG;EAExC,IAAI,OAAO,KAAK,aAAa,SAAS,GAAG;GACvC,IAAI,SAAS,GAAG;IACd,eAAe;IACf;GACF;GACA,IAAI,OAAO,kBAAkB;IAC3B,eAAe;IACf,mBAAmB;GACrB;EACF;CACF;CAGF,IAAI,cAAc;EAChB,MAAM,WAAW,YAAY,cAAc,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,42 +1,80 @@
1
+ //#region src/types.d.ts
1
2
  interface FormatQuantityOptions {
2
- /**
3
- * Output vulgar fractions, like "½" instead of "1/2", when appropriate.
4
- * Overrides the `fractionSlash` option.
5
- */
6
- vulgarFractions?: boolean;
7
- /**
8
- * Amount by which a number can deviate from the calculated quotient to be
9
- * considered a match. For example, 0.66 is close enough to 2 ÷ 3 (which
10
- * is 0.66666... repeating) to be considered equivalent so the function
11
- * will return "2/3". The smaller this number, the higher the likelihood that
12
- * the function will return a decimal instead of a fraction or mixed number.
13
- *
14
- * @default 0.0075
15
- */
16
- tolerance?: number;
17
- /**
18
- * Output the fraction slash character (⁄) instead of the "solidus"
19
- * slash (/) for fractions. Results appear like "1⁄2" instead of "1/2".
20
- * Overridden by the `vulgarFractions` option.
21
- */
22
- fractionSlash?: boolean;
23
- /**
24
- * Output in Roman numerals. Provided value must be between 1 and 3999, inclusive.
25
- * Decimal values will be ignored (`Math.floor` is used to remove them). Overrides
26
- * all other options.
27
- */
28
- romanNumerals?: boolean;
3
+ /**
4
+ * Output vulgar fractions, like "½" instead of "1/2", when appropriate.
5
+ * Overrides the `fractionSlash` option.
6
+ *
7
+ * @default false
8
+ */
9
+ vulgarFractions?: boolean;
10
+ /**
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;
26
+ /**
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
+ */
33
+ fractionSlash?: boolean;
34
+ /**
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
+ */
41
+ romanNumerals?: boolean;
42
+ /**
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
+ */
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;
29
61
  }
62
+ /**
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
+ */
67
+ type ResolvedFormatQuantityOptions = Required<Omit<FormatQuantityOptions, "separator">> & Pick<FormatQuantityOptions, "separator">;
30
68
  /**
31
69
  * Function signature of {@link formatQuantity}.
32
70
  */
33
71
  interface FormatQuantity {
34
- (qty: string | number, options?: boolean | FormatQuantityOptions): string | null;
72
+ (qty: string | number | bigint, options?: boolean | FormatQuantityOptions): string | null;
35
73
  }
36
74
  /** Any numeric character. */
37
- type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
75
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
38
76
  /** Any numeric character except '0'. */
39
- type NonZeroDigit = Exclude<Digit, '0'>;
77
+ type NonZeroDigit = Exclude<Digit, "0">;
40
78
  /**
41
79
  * Fraction string with either one or two numeric characters in both the
42
80
  * numerator and denominator (but not two characters in the numerator while
@@ -46,27 +84,13 @@ type SimpleFraction = `${NonZeroDigit}/${NonZeroDigit}` | `${NonZeroDigit}/${Non
46
84
  /**
47
85
  * Odd numerator sixteenth fraction strings.
48
86
  */
49
- type Sixteenth = `${'1' | '3' | '5' | '7' | '9' | '11' | '13' | '15'}/16`;
87
+ type Sixteenth = `${"1" | "3" | "5" | "7" | "9" | "11" | "13" | "15"}/16`;
50
88
  /**
51
89
  * Unicode vulgar fraction code points.
52
90
  */
53
- type VulgarFraction = '¼' | '½' | '¾' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '';
54
- /** @hidden */
55
- type FormatQuantityTests = Record<string, ([Parameters<FormatQuantity>[0], ReturnType<FormatQuantity>] | [
56
- Parameters<FormatQuantity>[0],
57
- ReturnType<FormatQuantity>,
58
- Parameters<FormatQuantity>[1]
59
- ])[]>;
60
-
61
- /**
62
- * Formats a number (or string that appears to be a number)
63
- * as one would see it written in imperial measurements, e.g.
64
- * "1 1/2" instead of "1.5". To use vulgar fraction characters
65
- * like "½", pass `true` as the second argument. For other options
66
- * see {@link FormatQuantityOptions}.
67
- */
68
- declare const formatQuantity: FormatQuantity;
69
-
91
+ type VulgarFraction = "¼" | "½" | "¾" | "" | "" | "" | "" | "" | "" | "" | "" | "" | "" | "" | "" | "" | "" | "";
92
+ //#endregion
93
+ //#region src/constants.d.ts
70
94
  /**
71
95
  * Default tolerance used by {@link formatQuantity} when determining if a number
72
96
  * is close enough to a fraction value to be considered equivalent.
@@ -75,39 +99,33 @@ declare const defaultTolerance: 0.0075;
75
99
  /**
76
100
  * Default options for {@link formatQuantity}.
77
101
  */
78
- declare const defaultOptions: {
79
- readonly vulgarFractions: false;
80
- readonly tolerance: 0.0075;
81
- readonly fractionSlash: false;
82
- readonly romanNumerals: false;
83
- };
102
+ declare const defaultOptions: Readonly<ResolvedFormatQuantityOptions>;
84
103
  /**
85
104
  * Map of vulgar fractions to their traditional ASCII equivalents.
86
105
  */
87
- declare const vulgarToAsciiMap: {
88
- readonly '\u00BC': "1/4";
89
- readonly '\u00BD': "1/2";
90
- readonly '\u00BE': "3/4";
91
- readonly '\u2150': "1/7";
92
- readonly '\u2151': "1/9";
93
- readonly '\u2152': "1/10";
94
- readonly '\u2153': "1/3";
95
- readonly '\u2154': "2/3";
96
- readonly '\u2155': "1/5";
97
- readonly '\u2156': "2/5";
98
- readonly '\u2157': "3/5";
99
- readonly '\u2158': "4/5";
100
- readonly '\u2159': "1/6";
101
- readonly '\u215A': "5/6";
102
- readonly '\u215B': "1/8";
103
- readonly '\u215C': "3/8";
104
- readonly '\u215D': "5/8";
105
- readonly '\u215E': "7/8";
106
- };
106
+ declare const vulgarToAsciiMap: Readonly<Record<VulgarFraction, SimpleFraction>>;
107
107
  /**
108
- * Map of "close enough" decimal values to the {@link VulgarFraction} or
109
- * {@link Sixteenth} fraction string matches.
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.
110
111
  */
111
- declare const fractionDecimalMatches: ([number, "⅓"] | [number, "⅔"] | [number, "⅕"] | [number, "⅖"] | [number, "⅗"] | [number, "⅘"] | [number, "⅙"] | [number, "⅚"] | [number, "⅐"] | [number, "⅑"] | [number, "⅒"] | [number, "⅛"] | [number, "¼"] | [number, "⅜"] | [number, "½"] | [number, "⅝"] | [number, "¾"] | [number, "⅞"] | [number, "1/16"] | [number, "3/16"] | [number, "5/16"] | [number, "7/16"] | [number, "9/16"] | [number, "11/16"] | [number, "13/16"] | [number, "15/16"])[];
112
-
113
- export { type Digit, type FormatQuantity, type FormatQuantityOptions, type FormatQuantityTests, type NonZeroDigit, type SimpleFraction, type Sixteenth, type VulgarFraction, defaultOptions, defaultTolerance, formatQuantity, fractionDecimalMatches, vulgarToAsciiMap };
112
+ declare const fractionDecimalMatches: readonly (readonly [number, VulgarFraction | Sixteenth])[];
113
+ //#endregion
114
+ //#region src/formatQuantity.d.ts
115
+ /**
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;
121
+ /**
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
+ */
128
+ declare const formatQuantity: FormatQuantity;
129
+ //#endregion
130
+ export { Digit, FormatQuantity, FormatQuantityOptions, NonZeroDigit, ResolvedFormatQuantityOptions, SimpleFraction, Sixteenth, VulgarFraction, defaultOptions, defaultTolerance, formatQuantity, formatRomanNumerals, fractionDecimalMatches, vulgarToAsciiMap };
131
+ //# sourceMappingURL=format-quantity.production.d.mts.map