-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
83 lines (68 loc) · 1.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
module.exports = {
/**
* Detect the type of `value`. Returns 'integer', 'float', 'boolean' or 'string'; defaults to 'string'.
*
* @param {*} value
*
* @returns {String}
*/
detect : function (value) {
value += '';
if (value.search(/^\-?\d+$/) > -1) {
return 'integer';
}
if (value.search(/^\-?\d+\.\d+[\d.]*$/) > -1) {
return 'float';
}
if ('false' === value || 'true' === value) {
return 'boolean';
}
if (value.search(/^\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z?$/) > -1) {
return 'datetime';
}
return 'string';
},
/**
* Cast `value` to given `type`.
*
* @param {*} value
* @param {String} [type]
*
* @returns {*}
*/
cast : function (value, type) {
type = type || 'smart';
switch (type) {
case 'boolean':
case 'bool':
if (typeof value !== 'string') {
value = !!value;
} else {
value = ['null', 'undefined', '0', 'false'].indexOf(value) === -1;
}
break;
case 'string':
case 'text':
value = this.cast(value, 'boolean') ? value + '' : null
break;
case 'date':
case 'datetime':
value = new Date(value);
break;
case 'int':
case 'integer':
case 'number':
value = ~~value;
break;
case 'float':
value = parseFloat(value);
break;
case 'smart':
value = this.cast(value, this.detect(value));
break;
default:
throw new Error('Expected valid casting type.');
}
return value;
}
};