-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhelpers.js
227 lines (207 loc) · 5.51 KB
/
helpers.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
var Module = require('module');
var path = require('path');
var fs = require('fs');
var crypto = require('crypto');
var jsonschema = require('jsonschema');
var chalk = require('chalk');
function randKey(length, charset){
var text = "";
if (!length) length = 8;
if (!charset) charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < length; i++ ){
text += charset.charAt(Math.floor(Math.random() * charset.length));
}
return text;
};
function requireFromString(code, filename){
// taken from https://github.com/floatdrop/require-from-string
filename = filename || '';
var paths = Module._nodeModulePaths(path.dirname(filename));
var m = new Module(filename, module.parent);
m.filename = filename;
m.paths = paths;
m._compile(code, filename);
return m.exports;
};
function defer(){
var deferred = {
promise: null,
resolve: null,
reject: null
};
deferred.promise = new Promise(function(resolve, reject){
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
};
function indent(len){
return ' '.repeat(len);
};
function measureSync(func, args){
var started = Date.now();
var result = func.apply(this, args);
var elapsed = Date.now() - started;
return {
result: result,
elapsed: elapsed
}
};
function StopWatch(){
if (!(this instanceof StopWatch)) return new StopWatch();
this.started = null;
this.ended = null;
}
StopWatch.prototype.start = function(){
this.ended = null, this.started = Date.now();
return this;
}
StopWatch.prototype.stop = function(){
this.ended = Date.now(), this.elapsed = (this.ended - this.started);
return this;
}
var CONFIDENCE_Z = {
'80': 1.282,
'85': 1.440,
'90': 1.645,
'95': 1.960,
'99': 2.576,
'99.5': 2.807,
'99.9': 3.291
}
function analyzeArray(vals, conf){
conf = conf || '95';
var min = Infinity, max = -Infinity;
var mean = vals.reduce(function(acc, item){
if (item < min) min = item;
if (item > max) max = item;
return item + acc
}, 0) / vals.length;
var stdev = Math.sqrt( vals.reduce(function(acc, item){ return acc + Math.pow(item - mean, 2) }, 0) / vals.length );
var confidence = CONFIDENCE_Z[conf] * stdev / Math.sqrt(vals.length);
return {
min: min,
max: max,
mean: mean,
stdev: stdev,
confidence: confidence
}
}
// Wrapper around jsonschema.Validator
function validateJSON(){
var config, schema;
if (typeof arguments[0] === 'string'){
config = JSON.parse( fs.readFileSync(arguments[0]).toString() );
}
else if (typeof arguments[0] === 'object'){
config = arguments[0];
}
else {
throw 'Unsupported argument type for config (arguments[0])';
}
if (typeof arguments[1] === 'object'){
schema = arguments[1];
}
else {
throw 'Unsupported argument type for schema (arguments[1])';
}
var validator = new jsonschema.Validator();
var result = validator.validate(config, schema);
if (result.errors.length === 0){
return config;
}
else {
console.log("!!! Error validating configuration:");
for (var i=0; i < result.errors.length; i++){
console.log(result.errors[i].message);
}
throw "JSONValidationError";
}
}
function Debugger(entity){
this.entity = entity;
}
Debugger.prototype.log = function(){
var self = this;
var args = Array.from(arguments);
args = args.map(function(arg){
return chalk.yellow(self.entity)+'\t'+arg;
})
console.log.apply(null, args);
}
/** Compute the hash of a given string using the specified hashing algorithm
* default hashing algorithm = md5
*/
function checksum(content, algo){
algo = algo || 'md5';
var hash = crypto.createHash(algo);
hash.update(content);
return hash.digest('hex');
}
function checksumJSON(obj, algo){
return checksum(Object.keys(obj).sort().map(function(key){
if (typeof obj[key] === 'object') return key+':'+checksumJSON(obj[key], algo);
else return key+':'+obj[key];
}).join(','), algo)
}
function hash(content){
return crypto.createHash('md5').update(content).digest('hex');
}
/** Quickly Deep Copy an Object (WARNING: only works when object is pure JSON - i.e. contains no Function, Promise, Date, or other native objects) */
function deepCopy(obj){
return JSON.parse(JSON.stringify(obj));
}
function getNestedProperty(obj, tokens){
if (tokens.length > 0){
if (obj) return getNestedProperty(obj[tokens[0]], tokens.slice(1));
}
else return obj;
}
function setNestedProperty(obj, tokens, value){
if (tokens.length > 1){
if (obj[tokens[0]]) return setNestedProperty(obj[tokens[0]], tokens.slice(1), value);
throw new Error('Nested objects do not exist')
}
else obj[tokens[0]] = value;
}
function deleteNestedProperty(obj, tokens){
if (tokens.length > 1){
if (obj[tokens[0]]) return deleteNestedProperty(obj[tokens[0]], tokens.slice(1));
throw new Error('Nested objects do not exist')
}
else delete obj[tokens[0]];
}
function promiseSequence(promiseFactory, repetition){
if (repetition > 0){
return promiseFactory()
.then(function(result){
return promiseSequence(promiseFactory, repetition - 1)
.then(function(rest){
rest.unshift(result);
return rest;
})
})
}
else {
return Promise.resolve([]);
}
}
module.exports = {
randKey: randKey,
requireFromString: requireFromString,
defer: defer,
indent: indent,
measureSync: measureSync,
StopWatch: StopWatch,
analyzeArray: analyzeArray,
validateJSON: validateJSON,
Debugger: Debugger,
hash: hash,
checksum: checksum,
checksumJSON: checksumJSON,
deepCopy: deepCopy,
getNestedProperty: getNestedProperty,
setNestedProperty: setNestedProperty,
deleteNestedProperty: deleteNestedProperty,
promiseSequence: promiseSequence
}