1 | import { typeOf } from '../../utils/is.js';
|
2 | import { factory } from '../../utils/factory.js';
|
3 | import { noBignumber, noFraction } from '../../utils/noop.js';
|
4 | var name = 'numeric';
|
5 | var dependencies = ['number', '?bignumber', '?fraction'];
|
6 | export var createNumeric = /* #__PURE__ */factory(name, dependencies, (_ref) => {
|
7 | var {
|
8 | number: _number,
|
9 | bignumber,
|
10 | fraction
|
11 | } = _ref;
|
12 | var validInputTypes = {
|
13 | string: true,
|
14 | number: true,
|
15 | BigNumber: true,
|
16 | Fraction: true
|
17 | }; // Load the conversion functions for each output type
|
18 |
|
19 | var validOutputTypes = {
|
20 | number: x => _number(x),
|
21 | BigNumber: bignumber ? x => bignumber(x) : noBignumber,
|
22 | Fraction: fraction ? x => fraction(x) : noFraction
|
23 | };
|
24 | /**
|
25 | * Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.
|
26 | *
|
27 | * Syntax:
|
28 | *
|
29 | * math.numeric(x)
|
30 | *
|
31 | * Examples:
|
32 | *
|
33 | * math.numeric('4') // returns number 4
|
34 | * math.numeric('4', 'number') // returns number 4
|
35 | * math.numeric('4', 'BigNumber') // returns BigNumber 4
|
36 | * math.numeric('4', 'Fraction') // returns Fraction 4
|
37 | * math.numeric(4, 'Fraction') // returns Fraction 4
|
38 | * math.numeric(math.fraction(2, 5), 'number') // returns number 0.4
|
39 | *
|
40 | * See also:
|
41 | *
|
42 | * number, fraction, bignumber, string, format
|
43 | *
|
44 | * @param {string | number | BigNumber | Fraction } value
|
45 | * A numeric value or a string containing a numeric value
|
46 | * @param {string} outputType
|
47 | * Desired numeric output type.
|
48 | * Available values: 'number', 'BigNumber', or 'Fraction'
|
49 | * @return {number | BigNumber | Fraction}
|
50 | * Returns an instance of the numeric in the requested type
|
51 | */
|
52 |
|
53 | return function numeric(value, outputType) {
|
54 | var inputType = typeOf(value);
|
55 |
|
56 | if (!(inputType in validInputTypes)) {
|
57 | throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', '));
|
58 | }
|
59 |
|
60 | if (!(outputType in validOutputTypes)) {
|
61 | throw new TypeError('Cannot convert ' + value + ' to type "' + outputType + '"; valid output types are ' + Object.keys(validOutputTypes).join(', '));
|
62 | }
|
63 |
|
64 | if (outputType === inputType) {
|
65 | return value;
|
66 | } else {
|
67 | return validOutputTypes[outputType](value);
|
68 | }
|
69 | };
|
70 | }); |
\ | No newline at end of file |