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.
package/README.md CHANGED
@@ -1,18 +1,20 @@
1
1
  [![npm][badge-npm]](https://www.npmjs.com/package/format-quantity)
2
2
  ![workflow status](https://github.com/jakeboone02/format-quantity/actions/workflows/main.yml/badge.svg)
3
3
  [![codecov.io](https://codecov.io/github/jakeboone02/format-quantity/coverage.svg?branch=main)](https://codecov.io/github/jakeboone02/format-quantity?branch=main)
4
- [![downloads](https://img.shields.io/npm/dm/format-quantity.svg)](http://npm-stat.com/charts.html?package=format-quantity&from=2015-08-01)
5
- [![MIT License](https://img.shields.io/npm/l/format-quantity.svg)](http://opensource.org/licenses/MIT)
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
+ [![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
- - The return value will be `null` if the first argument is neither a number nor a string that evaluates to a number using `parseFloat`.
15
- - 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.
16
18
 
17
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._
18
20
  >
@@ -58,7 +60,7 @@ The second parameter to `formatQuantity` can be a `boolean` value or an options
58
60
  ### `vulgarFractions`
59
61
 
60
62
  | Type | Default |
61
- | --------- | ------: |
63
+ | --------- | ------- |
62
64
  | `boolean` | `false` |
63
65
 
64
66
  Returns vulgar fractions when appropriate. This option has the same effect as passing a plain `boolean` value as the second parameter.
@@ -74,33 +76,87 @@ Note: `formatQuantity` supports sixteenths, but no vulgar fraction characters ex
74
76
  ### `fractionSlash`
75
77
 
76
78
  | Type | Default |
77
- | --------- | ------: |
79
+ | --------- | ------- |
78
80
  | `boolean` | `false` |
79
81
 
80
- 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"`). This option is ignored if the `vulgarFractions` option is also `true`.
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`.
81
83
 
82
84
  ```js
83
- formatQuantity(3.875, { fractionSlash: true }); // "3 7⁄8"
85
+ formatQuantity(3.875, { fractionSlash: true }); // "3 ⁷⁄₈"
84
86
  formatQuantity(3.875, { fractionSlash: true, vulgarFractions: true }); // "3⅞"
85
87
  ```
86
88
 
89
+ ### `separator`
90
+
91
+ | Type | Default |
92
+ | -------- | ------- |
93
+ | `string` | N/A |
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"`).
96
+
97
+ ```js
98
+ formatQuantity(1.5, { separator: '-' }); // "1-1/2"
99
+ formatQuantity(1.5, { separator: ' ', vulgarFractions: true }); // "1 ½"
100
+ formatQuantity(1.5, { separator: '\u00a0' }); // "1\u00a01/2" (no-break space)
101
+ ```
102
+
87
103
  ### `tolerance`
88
104
 
89
- | Type | Default |
90
- | -------- | -------: |
91
- | `number` | `0.0075` |
105
+ | Type | Default |
106
+ | ----------------- | -------: |
107
+ | `number \| false` | `0.0075` |
92
108
 
93
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"`.
94
110
 
95
- 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.
96
114
 
97
115
  ```js
98
116
  // Low tolerance - returns a decimal since 0.333 is not close enough to 1/3
99
117
  formatQuantity(0.333, { tolerance: 0.00001 }); // "0.333"
100
- // High tolerance - matches "1/3" even for 3/10
101
- formatQuantity(0.3, { tolerance: 0.1 }); // "1/3"
102
- // *Way* too high tolerance - incorrect result because thirds get evaluated before halves
103
- 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
104
160
  ```
105
161
 
106
162
  ### `romanNumerals`
@@ -109,13 +165,17 @@ formatQuantity(0.5, { tolerance: 0.5 }); // "1/3"
109
165
  | --------- | ------: |
110
166
  | `boolean` | `false` |
111
167
 
112
- 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`.
113
169
 
114
170
  When this option is `true`, all other options are ignored.
115
171
 
116
172
  ```js
117
173
  formatQuantity(1214, { romanNumerals: true }); // "MCCXIV"
118
174
  formatQuantity(12.14, { romanNumerals: true, vulgarFractions: true }); // "XII"
175
+ formatQuantity(4000, { romanNumerals: true }); // null
176
+ formatQuantity(-1, { romanNumerals: true }); // null
119
177
  ```
120
178
 
121
- [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,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.cjs.development.d.ts.map