-
Notifications
You must be signed in to change notification settings - Fork 199
/
util.js
124 lines (115 loc) · 2.51 KB
/
util.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
var toString = Object.prototype.toString;
var _ = module.exports = {};
/**
* is
* @param {*} source
* @param {string} type
* @returns {boolean}
*/
_.is = function(source, type){
return toString.call(source) === '[object ' + type + ']';
};
/**
* walk object and merge
* @param {Object} obj
* @param {Function} callback
* @param {Object} merge
*/
_.map = function(obj, callback, merge){
var index = 0;
for(var key in obj){
if(obj.hasOwnProperty(key)){
if(merge){
callback[key] = obj[key];
} else if(callback(key, obj[key], index++)) {
break;
}
}
}
};
/**
* merge target into source
* @param {*} source
* @param {*} target
* @returns {*}
*/
_.merge = function(source, target){
if(_.is(source, 'Object') && _.is(target, 'Object')){
_.map(target, function(key, value){
source[key] = _.merge(source[key], value);
});
} else {
source = target;
}
return source;
};
/**
* escape regexp chars
* @param {string} str
* @returns {string}
*/
_.escapeReg = function(str){
return str.replace(/[\.\\\+\*\?\[\^\]\$\(\){}=!<>\|:\/]/g, '\\$&');
};
/**
* pad a numeric string to two digits
* @param {string} str
* @returns {string}
*/
_.pad = function(str){
return ('0' + str).substr(-2);
};
/**
* convert millisecond into string like `2014-09-12 14:23:03`
* @param {Number} num
* @returns {string}
*/
_.getTimeString = function(num){
var d;
if(_.is(num, 'Date')){
d = num;
} else {
d = new Date();
d.setTime(num);
}
var day = [
d.getFullYear(),
_.pad(d.getMonth() + 1),
_.pad(d.getDate())
].join('-');
var time = [
_.pad(d.getHours()),
_.pad(d.getMinutes()),
_.pad(d.getSeconds())
].join(':');
return day + ' ' + time;
};
/**
* generate UUID
* @returns {string}
*/
_.unique = function(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16 | 0;
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
};
/**
* run mode, capture or diff or both
* @type {{CAPTURE: number, DIFF: number}}
*/
_.mode = {
CAPTURE: 1, // capture mode
DIFF : 2 // diff mode
};
/**
* log type
* @type {{DEBUG: string, WARNING: string, INFO: string, ERROR: string, NOTICE: string}}
*/
_.log = {
DEBUG: '<[debug]>',
WARNING: '<[warning]>',
INFO: '<[info]>',
ERROR: '<[error]>',
NOTICE: '<[notice]>'
};