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