format-quantity 2.1.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.
- package/README.md +24 -23
- package/dist/cjs/format-quantity.cjs.development.d.ts +107 -0
- package/dist/cjs/format-quantity.cjs.development.js +183 -180
- package/dist/cjs/format-quantity.cjs.development.js.map +1 -1
- package/dist/cjs/format-quantity.cjs.production.d.ts +107 -0
- package/dist/cjs/format-quantity.cjs.production.js +1 -1
- package/dist/cjs/format-quantity.cjs.production.js.map +1 -1
- package/dist/cjs/index.d.ts +1 -0
- package/dist/format-quantity.d.mts +107 -0
- package/dist/format-quantity.iife.umd.min.js +2 -0
- package/dist/format-quantity.iife.umd.min.js.map +1 -0
- package/dist/format-quantity.legacy-esm.d.ts +107 -0
- package/dist/format-quantity.legacy-esm.js +243 -165
- package/dist/format-quantity.legacy-esm.js.map +1 -1
- package/dist/format-quantity.mjs +178 -150
- package/dist/format-quantity.mjs.map +1 -1
- package/dist/format-quantity.production.d.mts +107 -0
- package/dist/format-quantity.production.mjs +1 -1
- package/dist/format-quantity.production.mjs.map +1 -1
- package/package.json +35 -22
- package/dist/format-quantity.d.ts +0 -83
- package/dist/format-quantity.umd.min.js +0 -2
- package/dist/format-quantity.umd.min.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
# format-quantity
|
|
2
|
-
|
|
3
1
|
[![npm][badge-npm]](https://www.npmjs.com/package/format-quantity)
|
|
4
2
|

|
|
5
3
|
[](https://codecov.io/github/jakeboone02/format-quantity?branch=main)
|
|
6
|
-
[](
|
|
7
|
-
[](
|
|
4
|
+
[](https://npm-stat.com/charts.html?package=format-quantity&from=2015-08-01)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
8
6
|
|
|
9
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".
|
|
10
8
|
|
|
9
|
+
**[Full documentation](https://jakeboone02.github.io/format-quantity/)**
|
|
10
|
+
|
|
11
11
|
Features:
|
|
12
12
|
|
|
13
|
-
- To use vulgar fraction characters like "⅞", pass `true` as the second argument
|
|
14
|
-
-
|
|
15
|
-
- The return value will be
|
|
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.
|
|
16
17
|
|
|
17
18
|
> _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
19
|
>
|
|
@@ -77,13 +78,27 @@ Note: `formatQuantity` supports sixteenths, but no vulgar fraction characters ex
|
|
|
77
78
|
| --------- | ------: |
|
|
78
79
|
| `boolean` | `false` |
|
|
79
80
|
|
|
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`.
|
|
81
|
+
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
82
|
|
|
82
83
|
```js
|
|
83
|
-
formatQuantity(3.875, { fractionSlash: true }); // "3
|
|
84
|
+
formatQuantity(3.875, { fractionSlash: true }); // "3 ⁷⁄₈"
|
|
84
85
|
formatQuantity(3.875, { fractionSlash: true, vulgarFractions: true }); // "3⅞"
|
|
85
86
|
```
|
|
86
87
|
|
|
88
|
+
### `separator`
|
|
89
|
+
|
|
90
|
+
| Type | Default |
|
|
91
|
+
| -------- | ------: |
|
|
92
|
+
| `string` | N/A |
|
|
93
|
+
|
|
94
|
+
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
|
+
```js
|
|
97
|
+
formatQuantity(1.5, { separator: '-' }); // "1-1/2"
|
|
98
|
+
formatQuantity(1.5, { separator: ' ', vulgarFractions: true }); // "1 ½"
|
|
99
|
+
formatQuantity(1.5, { separator: '\u00a0' }); // "1\u00a01/2" (no-break space)
|
|
100
|
+
```
|
|
101
|
+
|
|
87
102
|
### `tolerance`
|
|
88
103
|
|
|
89
104
|
| Type | Default |
|
|
@@ -118,18 +133,4 @@ formatQuantity(1214, { romanNumerals: true }); // "MCCXIV"
|
|
|
118
133
|
formatQuantity(12.14, { romanNumerals: true, vulgarFractions: true }); // "XII"
|
|
119
134
|
```
|
|
120
135
|
|
|
121
|
-
## Other exports
|
|
122
|
-
|
|
123
|
-
| Name | Type | Description |
|
|
124
|
-
| ------------------------ | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
125
|
-
| `defaultTolerance` | `number` | `0.0075` |
|
|
126
|
-
| `defaultOptions` | `type` | Object representing the default options |
|
|
127
|
-
| `fractionDecimalMatches` | <code>[number, VulgarFraction \| Sixteenth][]</code> | List of decimal values that are close enough to match the associated fraction (inputs are evaluated against the decimal values in the order of this array) |
|
|
128
|
-
| `vulgarToAsciiMap` | `object` | Map of vulgar fraction characters to their equivalent ASCII strings (`"⅓"` to `"1/3"`, `"⅞"` to `"7/8"`, etc.) |
|
|
129
|
-
| `formatRomanNumerals` | `function` | Formats a number as Roman numerals (used internally by `formatQuantity` when the `romanNumerals` option is `true`) |
|
|
130
|
-
| `FormatQuantityOptions` | `interface` | Shape of `formatQuantity`'s second parameter (if not a `boolean` value) |
|
|
131
|
-
| `SimpleFraction` | `type` | String template type for valid (positive, no division by zero) ASCII fraction strings with either one or two digits in the numerator and denominator each |
|
|
132
|
-
| `VulgarFraction` | `type` | The set of [vulgar fraction characters](https://en.wikipedia.org/wiki/Number_Forms) (`"\u00bc"`, `"\u00bd"`, `"\u00be"`, and `"\u2150"` through `"\u215e"`) |
|
|
133
|
-
| `Sixteenth` | `type` | Union type of all ASCII representations of odd-numbered sixteenth fractions less than one, (`"1/16"`, `"3/16"`, etc.) |
|
|
134
|
-
|
|
135
136
|
[badge-npm]: https://img.shields.io/npm/v/numeric-quantity.svg?cacheSeconds=3600&logo=npm
|
|
@@ -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.cjs.development.d.ts.map
|
|
@@ -1,192 +1,195 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
|
|
20
|
-
// src/index.ts
|
|
21
|
-
var src_exports = {};
|
|
22
|
-
__export(src_exports, {
|
|
23
|
-
default: () => src_default,
|
|
24
|
-
defaultOptions: () => defaultOptions,
|
|
25
|
-
defaultTolerance: () => defaultTolerance,
|
|
26
|
-
formatQuantity: () => formatQuantity,
|
|
27
|
-
fractionDecimalMatches: () => fractionDecimalMatches,
|
|
28
|
-
vulgarToAsciiMap: () => vulgarToAsciiMap
|
|
29
|
-
});
|
|
30
|
-
module.exports = __toCommonJS(src_exports);
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
let numeric_quantity = require("numeric-quantity");
|
|
31
3
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
4
|
+
//#region src/constants.ts
|
|
5
|
+
/**
|
|
6
|
+
* Default tolerance used by {@link formatQuantity} when determining if a number
|
|
7
|
+
* is close enough to a fraction value to be considered equivalent.
|
|
8
|
+
*/
|
|
9
|
+
const defaultTolerance = .0075;
|
|
10
|
+
/**
|
|
11
|
+
* Default options for {@link formatQuantity}.
|
|
12
|
+
*/
|
|
13
|
+
const defaultOptions = {
|
|
14
|
+
vulgarFractions: false,
|
|
15
|
+
tolerance: defaultTolerance,
|
|
16
|
+
fractionSlash: false,
|
|
17
|
+
romanNumerals: false
|
|
39
18
|
};
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
19
|
+
/**
|
|
20
|
+
* Map of vulgar fractions to their traditional ASCII equivalents.
|
|
21
|
+
*/
|
|
22
|
+
const vulgarToAsciiMap = {
|
|
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"
|
|
59
41
|
};
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
42
|
+
/**
|
|
43
|
+
* Map of "close enough" decimal values to the {@link VulgarFraction} or
|
|
44
|
+
* {@link Sixteenth} fraction string matches.
|
|
45
|
+
*/
|
|
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"]
|
|
87
73
|
];
|
|
88
74
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
75
|
+
//#endregion
|
|
76
|
+
//#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
|
+
const superscriptDigits = "⁰¹²³⁴⁵⁶⁷⁸⁹";
|
|
83
|
+
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;
|
|
100
88
|
};
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
89
|
+
const toSubscript = (s) => {
|
|
90
|
+
let r = "";
|
|
91
|
+
for (let i = 0; i < s.length; i++) r += subscriptDigits[+s[i]];
|
|
92
|
+
return r;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Applies the `vulgarFractions` or `fractionSlash` options as necessary.
|
|
96
|
+
*/
|
|
97
|
+
const getFraction = (vulgarFractionOrSixteenth, { fractionSlash, vulgarFractions }) => {
|
|
98
|
+
if (vulgarFractions) return vulgarFractionOrSixteenth;
|
|
99
|
+
const plainFraction = vulgarToAsciiMap[vulgarFractionOrSixteenth] ?? vulgarFractionOrSixteenth;
|
|
100
|
+
if (fractionSlash) {
|
|
101
|
+
const [num, den] = plainFraction.split("/");
|
|
102
|
+
return `${toSuperscript(num)}⁄${toSubscript(den)}`;
|
|
103
|
+
}
|
|
104
|
+
return plainFraction;
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* Merges options object with default options, converting boolean to object if necessary.
|
|
108
|
+
*/
|
|
109
|
+
const normalizeOptions = (options) => ({
|
|
110
|
+
...defaultOptions,
|
|
111
|
+
...typeof options === "boolean" ? { vulgarFractions: options } : options
|
|
104
112
|
});
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
113
|
+
const romanNumeralValueKey = [
|
|
114
|
+
"",
|
|
115
|
+
"C",
|
|
116
|
+
"CC",
|
|
117
|
+
"CCC",
|
|
118
|
+
"CD",
|
|
119
|
+
"D",
|
|
120
|
+
"DC",
|
|
121
|
+
"DCC",
|
|
122
|
+
"DCCC",
|
|
123
|
+
"CM",
|
|
124
|
+
"",
|
|
125
|
+
"X",
|
|
126
|
+
"XX",
|
|
127
|
+
"XXX",
|
|
128
|
+
"XL",
|
|
129
|
+
"L",
|
|
130
|
+
"LX",
|
|
131
|
+
"LXX",
|
|
132
|
+
"LXXX",
|
|
133
|
+
"XC",
|
|
134
|
+
"",
|
|
135
|
+
"I",
|
|
136
|
+
"II",
|
|
137
|
+
"III",
|
|
138
|
+
"IV",
|
|
139
|
+
"V",
|
|
140
|
+
"VI",
|
|
141
|
+
"VII",
|
|
142
|
+
"VIII",
|
|
143
|
+
"IX"
|
|
136
144
|
];
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
roman = `${romanNumeralValueKey[+digits.pop() + i * 10] || ""}${roman}`;
|
|
150
|
-
}
|
|
151
|
-
return `${Array(+digits.join("") + 1).join("M")}${roman}`;
|
|
145
|
+
/**
|
|
146
|
+
* Formats a number as Roman numerals. The number must be between
|
|
147
|
+
* 1 and 3999, inclusive.
|
|
148
|
+
*/
|
|
149
|
+
const formatRomanNumerals = (qty) => {
|
|
150
|
+
if (typeof qty !== "number" || isNaN(qty)) return null;
|
|
151
|
+
if (qty < 1 || qty >= 4e3) return "";
|
|
152
|
+
const digits = `${Math.floor(qty)}`.split("");
|
|
153
|
+
let roman = "";
|
|
154
|
+
let i = 3;
|
|
155
|
+
while (i--) roman = `${romanNumeralValueKey[+digits.pop() + i * 10] || ""}${roman}`;
|
|
156
|
+
return `${Array(+digits.join("") + 1).join("M")}${roman}`;
|
|
152
157
|
};
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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 = defaultOptions) => {
|
|
166
|
+
const qtyAsNumber = typeof qty === "string" ? (0, numeric_quantity.numericQuantity)(qty, {
|
|
167
|
+
round: false,
|
|
168
|
+
allowTrailingInvalid: true
|
|
169
|
+
}) : qty;
|
|
170
|
+
if (isNaN(qtyAsNumber) || qtyAsNumber === null) return null;
|
|
171
|
+
if (qtyAsNumber === 0) return "";
|
|
172
|
+
const opts = normalizeOptions(options ?? defaultOptions);
|
|
173
|
+
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;
|
|
179
|
+
if (decimalValue === 0) return `${qtyAsNumber}`;
|
|
180
|
+
for (const [num, vf] of fractionDecimalMatches) if (closeEnough(decimalValue, num, opts.tolerance)) {
|
|
181
|
+
const fraction = getFraction(vf, opts);
|
|
182
|
+
const isVulgar = fraction in vulgarToAsciiMap;
|
|
183
|
+
return `${sign}${wholeStr}${wholeStr ? opts.separator ?? (isVulgar ? "" : " ") : ""}${fraction}`;
|
|
184
|
+
}
|
|
185
|
+
return `${qtyAsNumber}`;
|
|
180
186
|
};
|
|
181
187
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
fractionDecimalMatches,
|
|
190
|
-
vulgarToAsciiMap
|
|
191
|
-
});
|
|
188
|
+
//#endregion
|
|
189
|
+
exports.defaultOptions = defaultOptions;
|
|
190
|
+
exports.defaultTolerance = defaultTolerance;
|
|
191
|
+
exports.formatQuantity = formatQuantity;
|
|
192
|
+
exports.formatRomanNumerals = formatRomanNumerals;
|
|
193
|
+
exports.fractionDecimalMatches = fractionDecimalMatches;
|
|
194
|
+
exports.vulgarToAsciiMap = vulgarToAsciiMap;
|
|
192
195
|
//# sourceMappingURL=format-quantity.cjs.development.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"file":"format-quantity.cjs.development.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,mBAAmB;;;;AAKhC,MAAa,iBAAgD;CAC3D,iBAAiB;CACjB,WAAW;CACX,eAAe;CACf,eAAe;CAChB;;;;AAKD,MAAa,mBAA2D;CACtE,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACN;;;;;AAMD,MAAa,yBAAiE;CAC5E,CAAC,KAAM,IAAI;CACX,CAAC,KAAM,IAAI;CACX,CAAC,IAAK,IAAI;CACV,CAAC,IAAK,IAAI;CACV,CAAC,IAAK,IAAI;CACV,CAAC,IAAK,IAAI;CACV,CAAC,MAAO,IAAI;CACZ,CAAC,MAAO,IAAI;CACZ,CAAC,MAAO,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