1 | import { factory } from '../utils/factory'
|
2 | import { deepMap } from '../utils/collection'
|
3 |
|
4 | const name = 'boolean'
|
5 | const dependencies = ['typed']
|
6 |
|
7 | export const createBoolean = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => {
|
8 | /**
|
9 | * Create a boolean or convert a string or number to a boolean.
|
10 | * In case of a number, `true` is returned for non-zero numbers, and `false` in
|
11 | * case of zero.
|
12 | * Strings can be `'true'` or `'false'`, or can contain a number.
|
13 | * When value is a matrix, all elements will be converted to boolean.
|
14 | *
|
15 | * Syntax:
|
16 | *
|
17 | * math.boolean(x)
|
18 | *
|
19 | * Examples:
|
20 | *
|
21 | * math.boolean(0) // returns false
|
22 | * math.boolean(1) // returns true
|
23 | * math.boolean(-3) // returns true
|
24 | * math.boolean('true') // returns true
|
25 | * math.boolean('false') // returns false
|
26 | * math.boolean([1, 0, 1, 1]) // returns [true, false, true, true]
|
27 | *
|
28 | * See also:
|
29 | *
|
30 | * bignumber, complex, index, matrix, string, unit
|
31 | *
|
32 | * @param {string | number | boolean | Array | Matrix | null} value A value of any type
|
33 | * @return {boolean | Array | Matrix} The boolean value
|
34 | */
|
35 | const bool = typed(name, {
|
36 | '': function () {
|
37 | return false
|
38 | },
|
39 |
|
40 | 'boolean': function (x) {
|
41 | return x
|
42 | },
|
43 |
|
44 | 'number': function (x) {
|
45 | return !!x
|
46 | },
|
47 |
|
48 | 'null': function (x) {
|
49 | return false
|
50 | },
|
51 |
|
52 | 'BigNumber': function (x) {
|
53 | return !x.isZero()
|
54 | },
|
55 |
|
56 | 'string': function (x) {
|
57 | // try case insensitive
|
58 | const lcase = x.toLowerCase()
|
59 | if (lcase === 'true') {
|
60 | return true
|
61 | } else if (lcase === 'false') {
|
62 | return false
|
63 | }
|
64 |
|
65 | // test whether value is a valid number
|
66 | const num = Number(x)
|
67 | if (x !== '' && !isNaN(num)) {
|
68 | return !!num
|
69 | }
|
70 |
|
71 | throw new Error('Cannot convert "' + x + '" to a boolean')
|
72 | },
|
73 |
|
74 | 'Array | Matrix': function (x) {
|
75 | return deepMap(x, bool)
|
76 | }
|
77 | })
|
78 |
|
79 | return bool
|
80 | })
|