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