format-quantity 3.0.0 → 3.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format-quantity.iife.umd.min.js","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":"+FAWA,IAAa,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,CACX,CAAC,GAAK,IAAI,CACV,CAAC,GAAK,IAAI,CACV,CAAC,GAAK,IAAI,CACV,CAAC,GAAK,IAAI,CACV,CAAC,KAAO,IAAI,CACZ,CAAC,KAAO,IAAI,CACZ,CAAC,KAAO,IAAI,CACZ,CAAC,KAAO,IAAI,CACZ,CAAC,GAAK,IAAI,CACV,CAAC,KAAO,IAAI,CACZ,CAAC,IAAM,IAAI,CACX,CAAC,KAAO,IAAI,CACZ,CAAC,GAAK,IAAI,CACV,CAAC,KAAO,IAAI,CACZ,CAAC,IAAM,IAAI,CACX,CAAC,KAAO,IAAI,CACZ,CAA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lD,EACA,EAAU,IACP,CACH,IAAM,EACJ,OAAO,GAAQ,UAAA,EAAA,EAAA,iBACK,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"}
@@ -0,0 +1,107 @@
1
+ //#region src/types.d.ts
2
+ interface FormatQuantityOptions {
3
+ /**
4
+ * Output vulgar fractions, like "½" instead of "1/2", when appropriate.
5
+ * Overrides the `fractionSlash` option.
6
+ */
7
+ vulgarFractions?: boolean;
8
+ /**
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;
18
+ /**
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
+ */
23
+ fractionSlash?: boolean;
24
+ /**
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
+ */
29
+ romanNumerals?: boolean;
30
+ /**
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
+ */
36
+ separator?: string;
37
+ }
38
+ /**
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
+ */
43
+ type ResolvedFormatQuantityOptions = Required<Omit<FormatQuantityOptions, "separator">> & Pick<FormatQuantityOptions, "separator">;
44
+ /**
45
+ * Function signature of {@link formatQuantity}.
46
+ */
47
+ interface FormatQuantity {
48
+ (qty: string | number, options?: boolean | FormatQuantityOptions): string | null;
49
+ }
50
+ /** Any numeric character. */
51
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
52
+ /** Any numeric character except '0'. */
53
+ type NonZeroDigit = Exclude<Digit, "0">;
54
+ /**
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
+ */
59
+ type SimpleFraction = `${NonZeroDigit}/${NonZeroDigit}` | `${NonZeroDigit}/${NonZeroDigit}${Digit}` | `${NonZeroDigit}${Digit}/${NonZeroDigit}${Digit}`;
60
+ /**
61
+ * Odd numerator sixteenth fraction strings.
62
+ */
63
+ type Sixteenth = `${"1" | "3" | "5" | "7" | "9" | "11" | "13" | "15"}/16`;
64
+ /**
65
+ * Unicode vulgar fraction code points.
66
+ */
67
+ type VulgarFraction = "¼" | "½" | "¾" | "⅐" | "⅑" | "⅒" | "⅓" | "⅔" | "⅕" | "⅖" | "⅗" | "⅘" | "⅙" | "⅚" | "⅛" | "⅜" | "⅝" | "⅞";
68
+ /** @hidden */
69
+ type FormatQuantityTests = Record<string, ([Parameters<FormatQuantity>[0], ReturnType<FormatQuantity>] | [Parameters<FormatQuantity>[0], ReturnType<FormatQuantity>, Parameters<FormatQuantity>[1]])[]>;
70
+ //#endregion
71
+ //#region src/constants.d.ts
72
+ /**
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
+ */
76
+ declare const defaultTolerance: 0.0075;
77
+ /**
78
+ * Default options for {@link formatQuantity}.
79
+ */
80
+ declare const defaultOptions: ResolvedFormatQuantityOptions;
81
+ /**
82
+ * Map of vulgar fractions to their traditional ASCII equivalents.
83
+ */
84
+ declare const vulgarToAsciiMap: Record<VulgarFraction, SimpleFraction>;
85
+ /**
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][];
90
+ //#endregion
91
+ //#region src/formatQuantity.d.ts
92
+ /**
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;
97
+ /**
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
+ */
104
+ declare const formatQuantity: FormatQuantity;
105
+ //#endregion
106
+ export { Digit, FormatQuantity, FormatQuantityOptions, FormatQuantityTests, NonZeroDigit, ResolvedFormatQuantityOptions, SimpleFraction, Sixteenth, VulgarFraction, defaultOptions, defaultTolerance, formatQuantity, formatRomanNumerals, fractionDecimalMatches, vulgarToAsciiMap };
107
+ //# sourceMappingURL=format-quantity.legacy-esm.d.ts.map
@@ -1,172 +1,254 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
- var __hasOwnProp = Object.prototype.hasOwnProperty;
4
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __spreadValues = (a, b) => {
7
- for (var prop in b || (b = {}))
8
- if (__hasOwnProp.call(b, prop))
9
- __defNormalProp(a, prop, b[prop]);
10
- if (__getOwnPropSymbols)
11
- for (var prop of __getOwnPropSymbols(b)) {
12
- if (__propIsEnum.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- }
15
- return a;
16
- };
1
+ import { numericQuantity } from "numeric-quantity";
17
2
 
18
- // src/constants.ts
19
- var defaultTolerance = 75e-4;
20
- var defaultOptions = {
21
- vulgarFractions: false,
22
- tolerance: defaultTolerance,
23
- fractionSlash: false,
24
- romanNumerals: false
3
+ //#region src/constants.ts
4
+ /**
5
+ * Default tolerance used by {@link formatQuantity} when determining if a number
6
+ * is close enough to a fraction value to be considered equivalent.
7
+ */
8
+ const defaultTolerance = .0075;
9
+ /**
10
+ * Default options for {@link formatQuantity}.
11
+ */
12
+ const defaultOptions = {
13
+ vulgarFractions: false,
14
+ tolerance: defaultTolerance,
15
+ fractionSlash: false,
16
+ romanNumerals: false
25
17
  };
26
- var vulgarToAsciiMap = {
27
- "\xBC": "1/4",
28
- "\xBD": "1/2",
29
- "\xBE": "3/4",
30
- "\u2150": "1/7",
31
- "\u2151": "1/9",
32
- "\u2152": "1/10",
33
- "\u2153": "1/3",
34
- "\u2154": "2/3",
35
- "\u2155": "1/5",
36
- "\u2156": "2/5",
37
- "\u2157": "3/5",
38
- "\u2158": "4/5",
39
- "\u2159": "1/6",
40
- "\u215A": "5/6",
41
- "\u215B": "1/8",
42
- "\u215C": "3/8",
43
- "\u215D": "5/8",
44
- "\u215E": "7/8"
18
+ /**
19
+ * Map of vulgar fractions to their traditional ASCII equivalents.
20
+ */
21
+ const vulgarToAsciiMap = {
22
+ "¼": "1/4",
23
+ "½": "1/2",
24
+ "¾": "3/4",
25
+ "": "1/7",
26
+ "": "1/9",
27
+ "": "1/10",
28
+ "": "1/3",
29
+ "": "2/3",
30
+ "": "1/5",
31
+ "": "2/5",
32
+ "": "3/5",
33
+ "": "4/5",
34
+ "": "1/6",
35
+ "": "5/6",
36
+ "": "1/8",
37
+ "⅜": "3/8",
38
+ "⅝": "5/8",
39
+ "⅞": "7/8"
45
40
  };
46
- var fractionDecimalMatches = [
47
- [0.33, "\u2153"],
48
- [0.66, "\u2154"],
49
- [0.2, "\u2155"],
50
- [0.4, "\u2156"],
51
- [0.6, "\u2157"],
52
- [0.8, "\u2158"],
53
- [0.166, "\u2159"],
54
- [0.833, "\u215A"],
55
- [0.143, "\u2150"],
56
- [0.111, "\u2151"],
57
- [0.1, "\u2152"],
58
- [0.125, "\u215B"],
59
- [0.25, "\xBC"],
60
- [0.375, "\u215C"],
61
- [0.5, "\xBD"],
62
- [0.625, "\u215D"],
63
- [0.75, "\xBE"],
64
- [0.875, "\u215E"],
65
- [0.0625, "1/16"],
66
- [0.1875, "3/16"],
67
- [0.3125, "5/16"],
68
- [0.4375, "7/16"],
69
- [0.5625, "9/16"],
70
- [0.6875, "11/16"],
71
- [0.8125, "13/16"],
72
- [0.9375, "15/16"]
41
+ /**
42
+ * Map of "close enough" decimal values to the {@link VulgarFraction} or
43
+ * {@link Sixteenth} fraction string matches.
44
+ */
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"]
73
72
  ];
74
73
 
75
- // src/formatQuantity.ts
76
- var closeEnough = (n1, n2, tolerance) => Math.abs(n1 - n2) < tolerance;
77
- var getFraction = (vulgarFractionOrSixteenth, { fractionSlash, vulgarFractions }) => {
78
- var _a;
79
- if (vulgarFractions) {
80
- return vulgarFractionOrSixteenth;
81
- }
82
- const plainFraction = (_a = vulgarToAsciiMap[vulgarFractionOrSixteenth]) != null ? _a : vulgarFractionOrSixteenth;
83
- if (fractionSlash) {
84
- return plainFraction.replace("/", "\u2044");
85
- }
86
- return plainFraction;
74
+ //#endregion
75
+ //#region \0@oxc-project+runtime@0.112.0/helpers/typeof.js
76
+ function _typeof(o) {
77
+ "@babel/helpers - typeof";
78
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
79
+ return typeof o;
80
+ } : function(o) {
81
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
82
+ }, _typeof(o);
83
+ }
84
+
85
+ //#endregion
86
+ //#region \0@oxc-project+runtime@0.112.0/helpers/toPrimitive.js
87
+ function toPrimitive(t, r) {
88
+ if ("object" != _typeof(t) || !t) return t;
89
+ var e = t[Symbol.toPrimitive];
90
+ if (void 0 !== e) {
91
+ var i = e.call(t, r || "default");
92
+ if ("object" != _typeof(i)) return i;
93
+ throw new TypeError("@@toPrimitive must return a primitive value.");
94
+ }
95
+ return ("string" === r ? String : Number)(t);
96
+ }
97
+
98
+ //#endregion
99
+ //#region \0@oxc-project+runtime@0.112.0/helpers/toPropertyKey.js
100
+ function toPropertyKey(t) {
101
+ var i = toPrimitive(t, "string");
102
+ return "symbol" == _typeof(i) ? i : i + "";
103
+ }
104
+
105
+ //#endregion
106
+ //#region \0@oxc-project+runtime@0.112.0/helpers/defineProperty.js
107
+ function _defineProperty(e, r, t) {
108
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
109
+ value: t,
110
+ enumerable: !0,
111
+ configurable: !0,
112
+ writable: !0
113
+ }) : e[r] = t, e;
114
+ }
115
+
116
+ //#endregion
117
+ //#region \0@oxc-project+runtime@0.112.0/helpers/objectSpread2.js
118
+ function ownKeys(e, r) {
119
+ var t = Object.keys(e);
120
+ if (Object.getOwnPropertySymbols) {
121
+ var o = Object.getOwnPropertySymbols(e);
122
+ r && (o = o.filter(function(r) {
123
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
124
+ })), t.push.apply(t, o);
125
+ }
126
+ return t;
127
+ }
128
+ function _objectSpread2(e) {
129
+ for (var r = 1; r < arguments.length; r++) {
130
+ var t = null != arguments[r] ? arguments[r] : {};
131
+ r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
132
+ _defineProperty(e, r, t[r]);
133
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
134
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
135
+ });
136
+ }
137
+ return e;
138
+ }
139
+
140
+ //#endregion
141
+ //#region src/formatQuantity.ts
142
+ /**
143
+ * Determines if two numbers are close enough to consider
144
+ * them equal for the purposes of this package.
145
+ */
146
+ const closeEnough = (n1, n2, tolerance) => Math.abs(n1 - n2) < tolerance;
147
+ const superscriptDigits = "⁰¹²³⁴⁵⁶⁷⁸⁹";
148
+ const subscriptDigits = "₀₁₂₃₄₅₆₇₈₉";
149
+ const toSuperscript = (s) => {
150
+ let r = "";
151
+ for (let i = 0; i < s.length; i++) r += superscriptDigits[+s[i]];
152
+ return r;
87
153
  };
88
- var normalizeOptions = (options) => __spreadValues(__spreadValues({}, defaultOptions), typeof options === "boolean" ? { vulgarFractions: options } : options);
89
- var romanNumeralValueKey = [
90
- "",
91
- "C",
92
- "CC",
93
- "CCC",
94
- "CD",
95
- "D",
96
- "DC",
97
- "DCC",
98
- "DCCC",
99
- "CM",
100
- "",
101
- "X",
102
- "XX",
103
- "XXX",
104
- "XL",
105
- "L",
106
- "LX",
107
- "LXX",
108
- "LXXX",
109
- "XC",
110
- "",
111
- "I",
112
- "II",
113
- "III",
114
- "IV",
115
- "V",
116
- "VI",
117
- "VII",
118
- "VIII",
119
- "IX"
120
- ];
121
- var formatRomanNumerals = (qty) => {
122
- if (typeof qty !== "number" || isNaN(qty)) {
123
- return null;
124
- }
125
- if (qty < 1 || qty >= 4e3) {
126
- return "";
127
- }
128
- const floored = Math.floor(qty);
129
- const digits = `${floored}`.split("");
130
- let roman = "";
131
- let i = 3;
132
- while (i--) {
133
- roman = `${romanNumeralValueKey[+digits.pop() + i * 10] || ""}${roman}`;
134
- }
135
- return `${Array(+digits.join("") + 1).join("M")}${roman}`;
154
+ const toSubscript = (s) => {
155
+ let r = "";
156
+ for (let i = 0; i < s.length; i++) r += subscriptDigits[+s[i]];
157
+ return r;
136
158
  };
137
- var formatQuantity = (qty, options = defaultOptions) => {
138
- const qtyAsNumber = typeof qty === "string" ? parseFloat(qty) : qty;
139
- if (isNaN(qtyAsNumber) || qtyAsNumber === null) {
140
- return null;
141
- }
142
- if (qtyAsNumber === 0) {
143
- return "";
144
- }
145
- const opts = normalizeOptions(options != null ? options : defaultOptions);
146
- if (opts.romanNumerals) {
147
- return formatRomanNumerals(qtyAsNumber);
148
- }
149
- const absoluteValue = Math.abs(qtyAsNumber);
150
- const flooredAbsVal = Math.floor(absoluteValue);
151
- const flooredAbsValStr = `${qtyAsNumber < 0 ? "-" : ""}${flooredAbsVal === 0 ? "" : `${flooredAbsVal} `}`;
152
- const decimalValue = absoluteValue - flooredAbsVal;
153
- if (decimalValue === 0) {
154
- return `${qtyAsNumber}`;
155
- }
156
- for (const [num, vf] of fractionDecimalMatches) {
157
- if (closeEnough(decimalValue, num, opts.tolerance)) {
158
- const fraction = getFraction(vf, opts);
159
- const int = fraction in vulgarToAsciiMap ? flooredAbsValStr.trim() : flooredAbsValStr;
160
- return `${int}${fraction}`;
161
- }
162
- }
163
- return `${qtyAsNumber}`;
159
+ /**
160
+ * Applies the `vulgarFractions` or `fractionSlash` options as necessary.
161
+ */
162
+ const getFraction = (vulgarFractionOrSixteenth, { fractionSlash, vulgarFractions }) => {
163
+ var _vulgarToAsciiMap;
164
+ if (vulgarFractions) return vulgarFractionOrSixteenth;
165
+ const plainFraction = (_vulgarToAsciiMap = vulgarToAsciiMap[vulgarFractionOrSixteenth]) !== null && _vulgarToAsciiMap !== void 0 ? _vulgarToAsciiMap : vulgarFractionOrSixteenth;
166
+ if (fractionSlash) {
167
+ const [num, den] = plainFraction.split("/");
168
+ return `${toSuperscript(num)}⁄${toSubscript(den)}`;
169
+ }
170
+ return plainFraction;
164
171
  };
165
- export {
166
- defaultOptions,
167
- defaultTolerance,
168
- formatQuantity,
169
- fractionDecimalMatches,
170
- vulgarToAsciiMap
172
+ /**
173
+ * Merges options object with default options, converting boolean to object if necessary.
174
+ */
175
+ const normalizeOptions = (options) => _objectSpread2(_objectSpread2({}, defaultOptions), typeof options === "boolean" ? { vulgarFractions: options } : options);
176
+ const romanNumeralValueKey = [
177
+ "",
178
+ "C",
179
+ "CC",
180
+ "CCC",
181
+ "CD",
182
+ "D",
183
+ "DC",
184
+ "DCC",
185
+ "DCCC",
186
+ "CM",
187
+ "",
188
+ "X",
189
+ "XX",
190
+ "XXX",
191
+ "XL",
192
+ "L",
193
+ "LX",
194
+ "LXX",
195
+ "LXXX",
196
+ "XC",
197
+ "",
198
+ "I",
199
+ "II",
200
+ "III",
201
+ "IV",
202
+ "V",
203
+ "VI",
204
+ "VII",
205
+ "VIII",
206
+ "IX"
207
+ ];
208
+ /**
209
+ * Formats a number as Roman numerals. The number must be between
210
+ * 1 and 3999, inclusive.
211
+ */
212
+ const formatRomanNumerals = (qty) => {
213
+ if (typeof qty !== "number" || isNaN(qty)) return null;
214
+ if (qty < 1 || qty >= 4e3) return "";
215
+ const digits = `${Math.floor(qty)}`.split("");
216
+ let roman = "";
217
+ let i = 3;
218
+ while (i--) roman = `${romanNumeralValueKey[+digits.pop() + i * 10] || ""}${roman}`;
219
+ return `${Array(+digits.join("") + 1).join("M")}${roman}`;
171
220
  };
221
+ /**
222
+ * Formats a number (or string that appears to be a number)
223
+ * as one would see it written in imperial measurements, e.g.
224
+ * "1 1/2" instead of "1.5". To use vulgar fraction characters
225
+ * like "½", pass `true` as the second argument. For other options
226
+ * see {@link FormatQuantityOptions}.
227
+ */
228
+ const formatQuantity = (qty, options = defaultOptions) => {
229
+ const qtyAsNumber = typeof qty === "string" ? numericQuantity(qty, {
230
+ round: false,
231
+ allowTrailingInvalid: true
232
+ }) : qty;
233
+ if (isNaN(qtyAsNumber) || qtyAsNumber === null) return null;
234
+ if (qtyAsNumber === 0) return "";
235
+ const opts = normalizeOptions(options !== null && options !== void 0 ? options : defaultOptions);
236
+ if (opts.romanNumerals) return formatRomanNumerals(qtyAsNumber);
237
+ const absoluteValue = Math.abs(qtyAsNumber);
238
+ const flooredAbsVal = Math.floor(absoluteValue);
239
+ const sign = qtyAsNumber < 0 ? "-" : "";
240
+ const wholeStr = flooredAbsVal === 0 ? "" : `${flooredAbsVal}`;
241
+ const decimalValue = absoluteValue - flooredAbsVal;
242
+ if (decimalValue === 0) return `${qtyAsNumber}`;
243
+ for (const [num, vf] of fractionDecimalMatches) if (closeEnough(decimalValue, num, opts.tolerance)) {
244
+ var _opts$separator;
245
+ const fraction = getFraction(vf, opts);
246
+ const isVulgar = fraction in vulgarToAsciiMap;
247
+ return `${sign}${wholeStr}${wholeStr ? (_opts$separator = opts.separator) !== null && _opts$separator !== void 0 ? _opts$separator : isVulgar ? "" : " " : ""}${fraction}`;
248
+ }
249
+ return `${qtyAsNumber}`;
250
+ };
251
+
252
+ //#endregion
253
+ export { defaultOptions, defaultTolerance, formatQuantity, formatRomanNumerals, fractionDecimalMatches, vulgarToAsciiMap };
172
254
  //# sourceMappingURL=format-quantity.legacy-esm.js.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;AAA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BAAiC,CAC5C,KACA,UAAU,mBACP;AAEH,QAAM,cAAc,OAAO,QAAQ,WAAW,WAAW,GAAG,IAAI;AAGhE,MAAI,MAAM,WAAW,KAAK,gBAAgB,MAAM;AAC9C,WAAO;AAAA,EACT;AAGA,MAAI,gBAAgB,GAAG;AACrB,WAAO;AAAA,EACT;AAKA,QAAM,OAAO,iBAAiB,4BAAW,cAAc;AAEvD,MAAI,KAAK,eAAe;AACtB,WAAO,oBAAoB,WAAW;AAAA,EACxC;AAEA,QAAM,gBAAgB,KAAK,IAAI,WAAW;AAC1C,QAAM,gBAAgB,KAAK,MAAM,aAAa;AAC9C,QAAM,mBAAmB,GAAG,cAAc,IAAI,MAAM,EAAE,GACpD,kBAAkB,IAAI,KAAK,GAAG,aAAa,GAC7C;AACA,QAAM,eAAe,gBAAgB;AAGrC,MAAI,iBAAiB,GAAG;AACtB,WAAO,GAAG,WAAW;AAAA,EACvB;AAEA,aAAW,CAAC,KAAK,EAAE,KAAK,wBAAwB;AAC9C,QAAI,YAAY,cAAc,KAAK,KAAK,SAAS,GAAG;AAClD,YAAM,WAAW,YAAY,IAAI,IAAI;AACrC,YAAM,MACJ,YAAY,mBACR,iBAAiB,KAAK,IACtB;AACN,aAAO,GAAG,GAAG,GAAG,QAAQ;AAAA,IAC1B;AAAA,EACF;AAEA,SAAO,GAAG,WAAW;AACvB;","names":[]}
1
+ {"version":3,"file":"format-quantity.legacy-esm.js","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,mB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