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.
package/README.md CHANGED
@@ -4,16 +4,17 @@
4
4
  [![downloads](https://img.shields.io/npm/dm/format-quantity.svg)](https://npm-stat.com/charts.html?package=format-quantity&from=2015-08-01)
5
5
  [![MIT License](https://img.shields.io/npm/l/format-quantity.svg)](https://opensource.org/licenses/MIT)
6
6
 
7
- Formats a number (or string that appears to be a number) as one would see it written in imperial measurements, e.g. "1 1/2" instead of "1.5".
7
+ Formats a `number` (or `bigint`, or `string` that appears to be a number) as one would see it written in imperial measurements, e.g. "1 1/2" instead of "1.5".
8
8
 
9
9
  **[Full documentation](https://jakeboone02.github.io/format-quantity/)**
10
10
 
11
11
  Features:
12
12
 
13
13
  - To use vulgar fraction characters like "⅞", pass `true` as the second argument. Other options like Roman numerals are described below.
14
- - String inputs are parsed with [`numeric-quantity`](https://www.npmjs.com/package/numeric-quantity), so mixed numbers (`"1 1/2"`), vulgar fractions (`"½"`), bare fractions (`"1/3"`), and comma/underscore-separated numbers (`"1,000"`) are all accepted in addition to plain decimal strings.
15
- - The return value will be `null` if the first argument is not a recognized numeric format.
16
- - The return value will be an empty string (`""`) if the first argument is `0` or `"0"`, which fits the primary use case of formatting recipe ingredient quantities.
14
+ - String inputs are parsed with [`numeric-quantity`](https://www.npmjs.com/package/numeric-quantity), so mixed numbers (`"1 1/2"`), vulgar fractions (`"½"`), bare fractions (`"1/3"`), and comma- or underscore-separated numbers (`"1,000"`) are all accepted in addition to plain decimal strings.
15
+ - The return value will be `null` if the first argument is not a `number`, `string`, or `bigint`, or is a string with no recognizable numeric portion at the start. Trailing junk is tolerated, so `formatQuantity("1.5 cups")` returns `"1 1/2"`.
16
+ - The return value will be an empty string (`""`) if the first argument is `0`, `0n`, or `"0"`, which fits the primary use case of formatting recipe ingredient quantities.
17
+ - Values too large or too small for positional notation are returned in JavaScript's exponential form (e.g. `formatQuantity(1e21)` is `"1e+21"`), and `Infinity`/`-Infinity` are stringified as-is. `bigint` inputs are never exponential; they stringify in full.
17
18
 
18
19
  > _For the inverse operation—converting a string to a `number`—check out [numeric-quantity](https://www.npmjs.com/package/numeric-quantity). It handles mixed numbers, vulgar fractions, comma/underscore separators, and Roman numerals._
19
20
  >
@@ -59,7 +60,7 @@ The second parameter to `formatQuantity` can be a `boolean` value or an options
59
60
  ### `vulgarFractions`
60
61
 
61
62
  | Type | Default |
62
- | --------- | ------: |
63
+ | --------- | ------- |
63
64
  | `boolean` | `false` |
64
65
 
65
66
  Returns vulgar fractions when appropriate. This option has the same effect as passing a plain `boolean` value as the second parameter.
@@ -75,7 +76,7 @@ Note: `formatQuantity` supports sixteenths, but no vulgar fraction characters ex
75
76
  ### `fractionSlash`
76
77
 
77
78
  | Type | Default |
78
- | --------- | ------: |
79
+ | --------- | ------- |
79
80
  | `boolean` | `false` |
80
81
 
81
82
  Uses the [fraction slash character](<https://en.wikipedia.org/wiki/Slash_(punctuation)#Fractions>) (`"\u2044"`) to separate the numerator and denominator instead of the regular "solidus" slash (`"\u002f"`), with Unicode superscript numerator and subscript denominator digits. This option is ignored if the `vulgarFractions` option is also `true`.
@@ -88,8 +89,8 @@ formatQuantity(3.875, { fractionSlash: true, vulgarFractions: true }); // "3⅞"
88
89
  ### `separator`
89
90
 
90
91
  | Type | Default |
91
- | -------- | ------: |
92
- | `string` | N/A |
92
+ | -------- | ------- |
93
+ | `string` | N/A |
93
94
 
94
95
  Overrides the string placed between the whole number and the fraction. When not specified, the default is `" "` (a space) for ASCII and fraction-slash fractions, and `""` (no space) for vulgar fractions. Common alternatives include a hyphen (`"-"`) and a no-break space (`"\u00a0"`).
95
96
 
@@ -101,21 +102,61 @@ formatQuantity(1.5, { separator: '\u00a0' }); // "1\u00a01/2" (no-break space)
101
102
 
102
103
  ### `tolerance`
103
104
 
104
- | Type | Default |
105
- | -------- | -------: |
106
- | `number` | `0.0075` |
105
+ | Type | Default |
106
+ | ----------------- | -------: |
107
+ | `number \| false` | `0.0075` |
107
108
 
108
109
  This option determines how close the decimal portion of a number has to be to the actual quotient of a fraction to be considered a match. For example, consider the fraction 1⁄3: $1 \div 3 = 0.\overline{333}$, repeating forever. The number `0.333` (exactly 333 thousandths) is not equivalent to 1⁄3, but it's very close. So even though $0.333 \neq 1 \div 3$, both `formatQuantity(0.333)` and `formatQuantity(1/3)` will return `"1/3"`.
109
110
 
110
- A lower tolerance increases the likelihood that `formatQuantity` will return a decimal representation instead of a fraction or mixed number since the matching algorithm will be stricter. An higher tolerance increases the likelihood that `formatQuantity` will return a fraction or mixed number, but at the risk of arbitrarily matching an incorrect fraction simply because it gets evaluated first (the export `fractionDecimalMatches` defines the order of evaluation).
111
+ The window is centered on the exact quotient and is checked against every candidate fraction; when more than one is within the window, the **closest** one wins regardless of evaluation order.
112
+
113
+ A lower tolerance increases the likelihood that `formatQuantity` will return a decimal representation instead of a fraction or mixed number since the matching algorithm will be stricter. A higher tolerance increases the likelihood that `formatQuantity` will return a fraction or mixed number, but at the risk of matching a fraction that is only loosely related to the input.
111
114
 
112
115
  ```js
113
116
  // Low tolerance - returns a decimal since 0.333 is not close enough to 1/3
114
117
  formatQuantity(0.333, { tolerance: 0.00001 }); // "0.333"
115
- // High tolerance - matches "1/3" even for 3/10
116
- formatQuantity(0.3, { tolerance: 0.1 }); // "1/3"
117
- // *Way* too high tolerance - incorrect result because thirds get evaluated before halves
118
- formatQuantity(0.5, { tolerance: 0.5 }); // "1/3"
118
+ // High tolerance - 0.3 is within 0.1 of both 5/16 and 1/3, and 5/16 is closer
119
+ formatQuantity(0.3, { tolerance: 0.1 }); // "5/16"
120
+ ```
121
+
122
+ Two values are special:
123
+
124
+ - `0` means **only exact quotients match**. Anything else falls through to its decimal representation.
125
+ - `false` **disables fraction matching entirely**, so every non-integer is returned as a decimal.
126
+
127
+ ```js
128
+ formatQuantity(1.5, { tolerance: 0 }); // "1 1/2" (0.5 is exactly 1 ÷ 2)
129
+ formatQuantity(1.51, { tolerance: 0 }); // "1.51"
130
+ formatQuantity(1.5, { tolerance: false }); // "1.5"
131
+ ```
132
+
133
+ Any other value—a negative number, `NaN`, a numeric string, `null`, `undefined`—is ignored and the default is used instead.
134
+
135
+ ### `zeroFormat`
136
+
137
+ | Type | Default |
138
+ | -------- | ------- |
139
+ | `string` | `""` |
140
+
141
+ Specify the string to return when the input numerically evaluates to zero (`0`).
142
+
143
+ ```js
144
+ formatQuantity(0, { zeroFormat: '' }); // "" (default)
145
+ formatQuantity(0, { zeroFormat: '0' }); // "0"
146
+ formatQuantity(0, { zeroFormat: 'N/A' }); // "N/A"
147
+ ```
148
+
149
+ ### `allowTrailingInvalid`
150
+
151
+ | Type | Default |
152
+ | --------- | ------- |
153
+ | `boolean` | `true` |
154
+
155
+ If input is a `string`, ignore trailing non-numeric input (à la `parseFloat`). Set to `false` for strict parsing — any invalid characters will result in `null`.
156
+
157
+ ```js
158
+ formatQuantity('123abc', { allowTrailingInvalid: true }); // "123"
159
+ formatQuantity('123abc', { allowTrailingInvalid: false }); // null
119
160
  ```
120
161
 
121
162
  ### `romanNumerals`
@@ -124,13 +165,17 @@ formatQuantity(0.5, { tolerance: 0.5 }); // "1/3"
124
165
  | --------- | ------: |
125
166
  | `boolean` | `false` |
126
167
 
127
- Coerces the number into an integer using `Math.floor`, then formats the value as Roman numerals. The algorithm uses strict, modern rules, so the number must be between 1 and 3999 (inclusive).
168
+ Coerces the number into an integer using `Math.floor`, then formats the value as Roman numerals. The algorithm uses strict, modern rules, so the number must be between `1` and `3999` inclusive (or between `1n` and `3999n` — `bigint` is also allowed). Values outside that range return `null`.
128
169
 
129
170
  When this option is `true`, all other options are ignored.
130
171
 
131
172
  ```js
132
173
  formatQuantity(1214, { romanNumerals: true }); // "MCCXIV"
133
174
  formatQuantity(12.14, { romanNumerals: true, vulgarFractions: true }); // "XII"
175
+ formatQuantity(4000, { romanNumerals: true }); // null
176
+ formatQuantity(-1, { romanNumerals: true }); // null
134
177
  ```
135
178
 
136
- [badge-npm]: https://img.shields.io/npm/v/numeric-quantity.svg?cacheSeconds=3600&logo=npm
179
+ > _`formatQuantity(0, …)` returns `""` (or the configured `zeroFormat`) regardless of this option, since the zero rule is applied before options are processed._
180
+
181
+ [badge-npm]: https://img.shields.io/npm/v/format-quantity.svg?cacheSeconds=3600&logo=npm
@@ -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.cjs.development.d.ts.map
@@ -1,6 +1,5 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let numeric_quantity = require("numeric-quantity");
3
-
4
3
  //#region src/constants.ts
5
4
  /**
6
5
  * Default tolerance used by {@link formatQuantity} when determining if a number
@@ -10,16 +9,18 @@ const defaultTolerance = .0075;
10
9
  /**
11
10
  * Default options for {@link formatQuantity}.
12
11
  */
13
- const defaultOptions = {
12
+ const defaultOptions = Object.freeze({
14
13
  vulgarFractions: false,
15
14
  tolerance: defaultTolerance,
16
15
  fractionSlash: false,
17
- romanNumerals: false
18
- };
16
+ romanNumerals: false,
17
+ zeroFormat: "",
18
+ allowTrailingInvalid: true
19
+ });
19
20
  /**
20
21
  * Map of vulgar fractions to their traditional ASCII equivalents.
21
22
  */
22
- const vulgarToAsciiMap = {
23
+ const vulgarToAsciiMap = Object.freeze({
23
24
  "¼": "1/4",
24
25
  "½": "1/2",
25
26
  "¾": "3/4",
@@ -38,59 +39,46 @@ const vulgarToAsciiMap = {
38
39
  "⅜": "3/8",
39
40
  "⅝": "5/8",
40
41
  "⅞": "7/8"
41
- };
42
+ });
42
43
  /**
43
- * Map of "close enough" decimal values to the {@link VulgarFraction} or
44
- * {@link Sixteenth} fraction string matches.
44
+ * Map of "close enough" values to the {@link VulgarFraction} or {@link Sixteenth} fraction
45
+ * string matches. The value +/- the `tolerance` option (or {@link defaultTolerance} if not
46
+ * specified) is considered close enough to match the fraction.
45
47
  */
46
- const fractionDecimalMatches = [
47
- [.33, ""],
48
- [.66, ""],
49
- [.2, ""],
50
- [.4, ""],
51
- [.6, ""],
52
- [.8, ""],
53
- [.166, ""],
54
- [.833, ""],
55
- [.143, ""],
56
- [.111, ""],
57
- [.1, ""],
58
- [.125, ""],
59
- [.25, "¼"],
60
- [.375, ""],
61
- [.5, "½"],
62
- [.625, ""],
63
- [.75, "¾"],
64
- [.875, ""],
65
- [.0625, "1/16"],
66
- [.1875, "3/16"],
67
- [.3125, "5/16"],
68
- [.4375, "7/16"],
69
- [.5625, "9/16"],
70
- [.6875, "11/16"],
71
- [.8125, "13/16"],
72
- [.9375, "15/16"]
73
- ];
74
-
48
+ const fractionDecimalMatches = Object.freeze([
49
+ [1 / 16, "1/16"],
50
+ [1 / 10, ""],
51
+ [1 / 9, ""],
52
+ [1 / 8, ""],
53
+ [1 / 7, ""],
54
+ [1 / 6, ""],
55
+ [3 / 16, "3/16"],
56
+ [1 / 5, ""],
57
+ [1 / 4, "¼"],
58
+ [5 / 16, "5/16"],
59
+ [1 / 3, ""],
60
+ [3 / 8, ""],
61
+ [2 / 5, ""],
62
+ [7 / 16, "7/16"],
63
+ [1 / 2, "½"],
64
+ [9 / 16, "9/16"],
65
+ [3 / 5, ""],
66
+ [5 / 8, ""],
67
+ [2 / 3, ""],
68
+ [11 / 16, "11/16"],
69
+ [3 / 4, "¾"],
70
+ [4 / 5, ""],
71
+ [13 / 16, "13/16"],
72
+ [5 / 6, ""],
73
+ [7 / 8, ""],
74
+ [15 / 16, "15/16"]
75
+ ].map((entry) => Object.freeze(entry)));
75
76
  //#endregion
76
77
  //#region src/formatQuantity.ts
77
- /**
78
- * Determines if two numbers are close enough to consider
79
- * them equal for the purposes of this package.
80
- */
81
- const closeEnough = (n1, n2, tolerance) => Math.abs(n1 - n2) < tolerance;
82
78
  const superscriptDigits = "⁰¹²³⁴⁵⁶⁷⁸⁹";
83
79
  const subscriptDigits = "₀₁₂₃₄₅₆₇₈₉";
84
- const toSuperscript = (s) => {
85
- let r = "";
86
- for (let i = 0; i < s.length; i++) r += superscriptDigits[+s[i]];
87
- return r;
88
- };
89
- const toSubscript = (s) => {
90
- let r = "";
91
- for (let i = 0; i < s.length; i++) r += subscriptDigits[+s[i]];
92
- return r;
93
- };
80
+ const toSuperscript = (s) => [...s].map((c) => superscriptDigits[+c]).join("");
81
+ const toSubscript = (s) => [...s].map((c) => subscriptDigits[+c]).join("");
94
82
  /**
95
83
  * Applies the `vulgarFractions` or `fractionSlash` options as necessary.
96
84
  */
@@ -104,13 +92,25 @@ const getFraction = (vulgarFractionOrSixteenth, { fractionSlash, vulgarFractions
104
92
  return plainFraction;
105
93
  };
106
94
  /**
95
+ * Only `false` (matching disabled) or a non-negative number is a valid
96
+ * `tolerance`. Everything else—negative numbers, `NaN`, non-numbers,
97
+ * `null`, `undefined`—resolves to {@link defaultTolerance}.
98
+ */
99
+ const isValidTolerance = (tolerance) => tolerance === false || typeof tolerance === "number" && tolerance >= 0;
100
+ /**
107
101
  * Merges options object with default options, converting boolean to object if necessary.
108
102
  */
109
- const normalizeOptions = (options) => ({
110
- ...defaultOptions,
111
- ...typeof options === "boolean" ? { vulgarFractions: options } : options
112
- });
113
- const romanNumeralValueKey = [
103
+ const normalizeOptions = (options) => {
104
+ const opts = {
105
+ ...defaultOptions,
106
+ ...typeof options === "boolean" ? { vulgarFractions: options } : typeof options === "object" && options !== null ? options : {}
107
+ };
108
+ if (!isValidTolerance(opts.tolerance)) opts.tolerance = defaultOptions.tolerance;
109
+ if (typeof opts.zeroFormat !== "string") opts.zeroFormat = defaultOptions.zeroFormat;
110
+ if (opts.allowTrailingInvalid !== false) opts.allowTrailingInvalid = true;
111
+ return opts;
112
+ };
113
+ const romanNumeralsByPlace = [
114
114
  "",
115
115
  "C",
116
116
  "CC",
@@ -143,16 +143,17 @@ const romanNumeralValueKey = [
143
143
  "IX"
144
144
  ];
145
145
  /**
146
- * Formats a number as Roman numerals. The number must be between
147
- * 1 and 3999, inclusive.
146
+ * Formats a number or bigint as Roman numerals. The number must be between
147
+ * 1 and 3999, inclusive; any other value—including non-numbers,
148
+ * `NaN`, and non-finite numbers—yields `null`.
148
149
  */
149
- const formatRomanNumerals = (qty) => {
150
- if (typeof qty !== "number" || isNaN(qty)) return null;
151
- if (qty < 1 || qty >= 4e3) return "";
150
+ const formatRomanNumerals = (quantity) => {
151
+ if (typeof quantity !== "number" && typeof quantity !== "bigint" || !(quantity >= 1 && quantity < 4e3)) return null;
152
+ const qty = Number(quantity);
152
153
  const digits = `${Math.floor(qty)}`.split("");
153
154
  let roman = "";
154
155
  let i = 3;
155
- while (i--) roman = `${romanNumeralValueKey[+digits.pop() + i * 10] || ""}${roman}`;
156
+ while (i--) roman = `${romanNumeralsByPlace[+digits.pop() + i * 10] || ""}${roman}`;
156
157
  return `${Array(+digits.join("") + 1).join("M")}${roman}`;
157
158
  };
158
159
  /**
@@ -162,29 +163,46 @@ const formatRomanNumerals = (qty) => {
162
163
  * like "½", pass `true` as the second argument. For other options
163
164
  * see {@link FormatQuantityOptions}.
164
165
  */
165
- const formatQuantity = (qty, options = defaultOptions) => {
166
- const qtyAsNumber = typeof qty === "string" ? (0, numeric_quantity.numericQuantity)(qty, {
167
- round: false,
168
- allowTrailingInvalid: true
166
+ const formatQuantity = (qty, options) => {
167
+ if (typeof qty !== "number" && typeof qty !== "string" && typeof qty !== "bigint") return null;
168
+ const opts = normalizeOptions(options);
169
+ const qtyAsNumber = typeof qty !== "number" && typeof qty !== "bigint" ? (0, numeric_quantity.numericQuantity)(qty, {
170
+ allowTrailingInvalid: opts.allowTrailingInvalid,
171
+ romanNumerals: opts.romanNumerals,
172
+ bigIntOnOverflow: true,
173
+ round: false
169
174
  }) : qty;
170
- if (isNaN(qtyAsNumber) || qtyAsNumber === null) return null;
171
- if (qtyAsNumber === 0) return "";
172
- const opts = normalizeOptions(options ?? defaultOptions);
175
+ if (typeof qtyAsNumber === "number" && isNaN(qtyAsNumber)) return null;
176
+ if (Number(qtyAsNumber) === 0) return opts.zeroFormat;
173
177
  if (opts.romanNumerals) return formatRomanNumerals(qtyAsNumber);
174
- const absoluteValue = Math.abs(qtyAsNumber);
175
- const flooredAbsVal = Math.floor(absoluteValue);
176
- const sign = qtyAsNumber < 0 ? "-" : "";
177
- const wholeStr = flooredAbsVal === 0 ? "" : `${flooredAbsVal}`;
178
- const decimalValue = absoluteValue - flooredAbsVal;
178
+ const absoluteValue = typeof qtyAsNumber === "bigint" ? qtyAsNumber < 0n ? -qtyAsNumber : qtyAsNumber : Math.abs(qtyAsNumber);
179
+ const flooredAbsVal = typeof absoluteValue === "bigint" ? absoluteValue : Math.floor(absoluteValue);
180
+ const wholeNumberStr = `${flooredAbsVal || ""}`;
181
+ const decimalValue = typeof absoluteValue === "bigint" ? 0 : absoluteValue - flooredAbsVal;
179
182
  if (decimalValue === 0) return `${qtyAsNumber}`;
180
- for (const [num, vf] of fractionDecimalMatches) if (closeEnough(decimalValue, num, opts.tolerance)) {
181
- const fraction = getFraction(vf, opts);
183
+ let closestMatch = null;
184
+ let closestMatchDiff = Infinity;
185
+ if (opts.tolerance !== false) for (const [num, vf] of fractionDecimalMatches) {
186
+ const diff = Math.abs(decimalValue - num);
187
+ if (diff < opts.tolerance || diff === 0) {
188
+ if (diff === 0) {
189
+ closestMatch = vf;
190
+ break;
191
+ }
192
+ if (diff < closestMatchDiff) {
193
+ closestMatch = vf;
194
+ closestMatchDiff = diff;
195
+ }
196
+ }
197
+ }
198
+ if (closestMatch) {
199
+ const fraction = getFraction(closestMatch, opts);
182
200
  const isVulgar = fraction in vulgarToAsciiMap;
183
- return `${sign}${wholeStr}${wholeStr ? opts.separator ?? (isVulgar ? "" : " ") : ""}${fraction}`;
201
+ const sep = wholeNumberStr ? opts.separator ?? (isVulgar ? "" : " ") : "";
202
+ return `${qtyAsNumber < 0 ? "-" : ""}${wholeNumberStr}${sep}${fraction}`;
184
203
  }
185
204
  return `${qtyAsNumber}`;
186
205
  };
187
-
188
206
  //#endregion
189
207
  exports.defaultOptions = defaultOptions;
190
208
  exports.defaultTolerance = defaultTolerance;
@@ -192,4 +210,5 @@ exports.formatQuantity = formatQuantity;
192
210
  exports.formatRomanNumerals = formatRomanNumerals;
193
211
  exports.fractionDecimalMatches = fractionDecimalMatches;
194
212
  exports.vulgarToAsciiMap = vulgarToAsciiMap;
213
+
195
214
  //# sourceMappingURL=format-quantity.cjs.development.js.map