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 | 'boolean': function boolean(x) {
|
38 | return x;
|
39 | },
|
40 | 'number': function number(x) {
|
41 | return !!x;
|
42 | },
|
43 | 'null': function _null(x) {
|
44 | return false;
|
45 | },
|
46 | 'BigNumber': function BigNumber(x) {
|
47 | return !x.isZero();
|
48 | },
|
49 | 'string': function string(x) {
|
50 | // try case insensitive
|
51 | var lcase = x.toLowerCase();
|
52 |
|
53 | if (lcase === 'true') {
|
54 | return true;
|
55 | } else if (lcase === 'false') {
|
56 | return false;
|
57 | } // test whether value is a valid number
|
58 |
|
59 |
|
60 | var num = Number(x);
|
61 |
|
62 | if (x !== '' && !isNaN(num)) {
|
63 | return !!num;
|
64 | }
|
65 |
|
66 | throw new Error('Cannot convert "' + x + '" to a boolean');
|
67 | },
|
68 | 'Array | Matrix': function ArrayMatrix(x) {
|
69 | return deepMap(x, bool);
|
70 | }
|
71 | });
|
72 | return bool;
|
73 | }
|
74 |
|
75 | exports.name = 'boolean';
|
76 | exports.factory = factory; |
\ | No newline at end of file |