-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
86 lines (72 loc) · 1.31 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
84
85
86
module.exports = typecast;
/**
* Cast given `val` to `type`
*
* @param {Mixed} val
* @param {String} type
* @api public
*/
function typecast (val, type) {
var fn = typecast[type];
if (typeof fn != 'function') throw new Error('cannot cast to ' + type);
return fn(val);
}
/**
* Cast `val` to `String`
*
* @param {Mixed} val
* @api public
*/
typecast.string = function (val) {
if (null == val) return '';
return val.toString();
};
/**
* Cast `val` to `Number`
*
* @param {Mixed} val
* @api public
*/
typecast.number = function (val) {
var num = parseFloat(val);
return isNaN(num)
? 0
: num;
};
/**
* Cast `val` to a`Date`
*
* @param {Mixed} val
* @api public
*/
typecast.date = function (val) {
var date = new Date(val);
return isNaN(date.valueOf())
? new Date(0)
: date;
};
/**
* Cast `val` to `Array`
*
* @param {Mixed} val
* @api public
*/
typecast.array = function (val) {
if (val == null) return [];
if (val instanceof Array) return val;
if (typeof val != 'string') return [val];
var arr = val.split(',');
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].trim();
}
return arr;
};
/**
* Cast `val` to `Boolean`
*
* @param {Mixed} val
* @api public
*/
typecast.boolean = function (val) {
return !! val && val !== 'false' && val !== '0';
};