UNPKG

2.05 kBJavaScriptView Raw
1import { factory } from '../utils/factory'
2import { deepMap } from '../utils/collection'
3
4const name = 'number'
5const dependencies = ['typed']
6
7export const createNumber = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => {
8 /**
9 * Create a number or convert a string, boolean, or unit to a number.
10 * When value is a matrix, all elements will be converted to number.
11 *
12 * Syntax:
13 *
14 * math.number(value)
15 * math.number(unit, valuelessUnit)
16 *
17 * Examples:
18 *
19 * math.number(2) // returns number 2
20 * math.number('7.2') // returns number 7.2
21 * math.number(true) // returns number 1
22 * math.number([true, false, true, true]) // returns [1, 0, 1, 1]
23 * math.number(math.unit('52cm'), 'm') // returns 0.52
24 *
25 * See also:
26 *
27 * bignumber, boolean, complex, index, matrix, string, unit
28 *
29 * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
30 * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
31 * @return {number | Array | Matrix} The created number
32 */
33 const number = typed('number', {
34 '': function () {
35 return 0
36 },
37
38 number: function (x) {
39 return x
40 },
41
42 string: function (x) {
43 if (x === 'NaN') return NaN
44 const num = Number(x)
45 if (isNaN(num)) {
46 throw new SyntaxError('String "' + x + '" is no valid number')
47 }
48 return num
49 },
50
51 BigNumber: function (x) {
52 return x.toNumber()
53 },
54
55 Fraction: function (x) {
56 return x.valueOf()
57 },
58
59 Unit: function (x) {
60 throw new Error('Second argument with valueless unit expected')
61 },
62
63 null: function (x) {
64 return 0
65 },
66
67 'Unit, string | Unit': function (unit, valuelessUnit) {
68 return unit.toNumber(valuelessUnit)
69 },
70
71 'Array | Matrix': function (x) {
72 return deepMap(x, number)
73 }
74 })
75
76 return number
77})