-
Notifications
You must be signed in to change notification settings - Fork 1
/
vlug.js
621 lines (533 loc) · 18.3 KB
/
vlug.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/*
* Vlug
* Version 0.1.0
*/
(function() {
var context = this,
oldVlug = context.Vlug;
context.Vlug = {};
Vlug.noConflict = function() {
context.Vlug = oldVlug;
};
Vlug.initialContext = context;
(function() {
var apply = function(t, f) {
var to = t || {},
from = f || {},
prop;
for (prop in from) {
if (from.hasOwnProperty(prop)) {
to[prop] = from[prop];
}
}
return to;
};
var mix = function(t, f) {
var to = t,
from = f,
prop;
for (prop in from) {
if (from.hasOwnProperty(prop) && typeof to[prop] === 'undefined') {
to[prop] = from[prop];
}
}
return to;
};
var forEach = (function() {
var nativeForEach = Array.prototype.forEach;
if (nativeForEach) {
return function(arr, fn, context) {
nativeForEach.call(arr, fn, context);
};
}
return function(arr, fn, context) {
var i, len = arr.length;
for (i = 0; i < len; ++i) {
fn.call(context || this, arr[i], i, arr);
}
return arr;
};
})();
var isArray = (function() {
var nativeIsArray = Array.isArray;
if (nativeIsArray) {
return nativeIsArray;
}
return function(arr) {
return toString.call(arr) === '[object Array]';
};
})();
var arrayFrom = function(arrOrItem) {
if (Vlug.utils.Array.isArray(arrOrItem)) {
return arrOrItem;
}
return (typeof arrOrItem === 'undefined') ? [] : [arrOrItem];
};
var each = function(arrOrItem, fn, context) {
return forEach(arrayFrom(arrOrItem), fn, context);
};
var con = (function() {
var time = console.time,
timeEnd = console.timeEnd,
timeIds;
if (!time) {
timeIds = {};
time = function(id) {
timeIds[id] = new Date();
};
timeEnd = function(id) {
var millis = new Date().getTime() - timeIds[id].getTime();
delete timeIds.id;
console.log('%s : %ims', id, millis);
};
} else {
time = function(id) {
console.time.call(console, id);
};
timeEnd = function(id) {
console.timeEnd.call(console, id);
};
}
return {
time: time,
timeEnd: timeEnd
};
})();
var timeStamp = (function() {
if (typeof performance !== 'undefined' && performance.now) {
return function() {
return performance.now();
};
}
return function() {
return new Date().getTime();
};
})();
apply(Vlug, {
utils: {
apply: apply,
mix: mix,
Array: {
forEach: forEach,
each: each,
isArray: isArray,
from: arrayFrom
},
console: con,
timeStamp: timeStamp
},
mixins: {},
abstractFn: function() {
throw new Error('abstractFn must be implemented');
},
emptyFn: function() {}
});
})();
Vlug.mixins.TimeTracker = {
stampStart: function(id) {
this._initTimes();
if (this.log) {
Vlug.utils.console.time(id);
}
this._timeStamps[id] = Vlug.utils.timeStamp();
},
_initTimes: function() {
if (!this._timeStamps) {
this._timeStamps = {};
this._totalTimes = {};
}
},
stampEnd: function(id) {
var start = this._timeStamps[id],
currentRunTime = Vlug.utils.timeStamp() - start;
this._trackTime(id, currentRunTime);
if (this.log) {
Vlug.utils.console.timeEnd(id);
}
},
_trackTime: function(id, runtime) {
if (!this._totalTimes[id]) {
this._totalTimes[id] = {
iterationsRun: 0,
totalTime: 0
};
}
this._totalTimes[id].iterationsRun += this._getIterationsToAdd(id);
this._totalTimes[id].totalTime += runtime;
},
_getIterationsToAdd: Vlug.abstractFn,
getReport: function() {
return this._buildReportObject();
},
_buildReportObject: function() {
var prop, report = {};
for (prop in this._totalTimes) {
if (this._totalTimes.hasOwnProperty(prop)) {
report[prop] = Vlug.utils.apply({}, this._totalTimes[prop]);
report[prop].average = report[prop].totalTime / report[prop].iterationsRun;
}
}
return report;
}
};
/**
* @class Vlug.Runner
* Runs a set of functions for n number of iterations
* and keeps time info on the set of functions.
var arr = [1,2 3],
runner = new Vlug.Runner({
//defaults to true
log: true,
iterations: 10000,
functions: [{
fn: function() {
var a;
arr.forEach(function(value, index) {
a = value + index;
});
},
name: 'nativeForEach'
}, {
fn: function() {
var a;
Vlug.utils.Array.forEach(arr, function(value, index) {
a = value + index;
});
},
name: 'VlugForEach'
}, {
fn: function() {
var a, i = 0,
len = arr.length
for(; i < len; ++i) {
a = arr[i] + i;
}
},
name: 'forLoop'
}]
});
runner.run();
* would show console.time outputs to the console like:
nativeForEach: 7.304ms
VlugForEach: 8.032ms
forLoop: 0.796ms
*after calling run 2 more times runner.getReport() would return something like:
{
"nativeForEach": {
"iterationsRun": 30000,
"totalTime": 24.921000011090655,
"average": 0.0008307000003696885
},
"VlugForEach": {
"iterationsRun": 30000,
"totalTime": 14.927000003808644,
"average": 0.0004975666667936215
},
"forLoop": {
"iterationsRun": 30000,
"totalTime": 1.0809999948833138,
"average": 0.00003603333316277712
}
}
*/
Vlug.Runner = function(config) {
this.init(config);
};
Vlug.Runner.prototype = {
/**
* @cfg {Number} iterations
* The number of iterations for the function(s) to run.
*/
iterations: 10,
/**
* @cfg {Function|Function[]|{}|{}[]} functions
functions can either be functions or objects in the form of :
*@cfg functions.name {String} the identifier name for the function
*@cfg functions.fn {Function} (required) the function to call
functions: {
fn: function() {
var a,
arr = [1,2,3];
arr.forEach(function(value, index) {
a = value + index;
});
},
name: 'forEach'
}
*this is also a valid config:
functions: [function(){return 1;}, function(){return 2;}]
*/
/**
* @cfg {Boolean} log
* true to output console.time info
*/
log: true,
init: function(config) {
Vlug.utils.apply(this, config);
},
/**
* @method run
* Runs the configured functions for the configured amount
* of iterations. If log is true it will output console.time info
*/
run: function() {
Vlug.utils.Array.each(this.functions, function(functionOrObj, index) {
var name = functionOrObj.name,
fn;
if (name) {
fn = functionOrObj.fn || functionOrObj;
} else {
name = 'index:' + index;
fn = functionOrObj;
}
this._runFunction(fn, name);
}, this);
},
_runFunction: function(fn, name) {
this.stampStart(name);
this._runFunctionForIterations(fn);
this.stampEnd(name);
},
_runFunctionForIterations: function(fn) {
var iterations = this.iterations,
i = 0;
for (; i < iterations; ++i) {
fn();
}
},
/**
* Set the amount of iterations to run.
* @param {Number} iterations
*/
setIterations: function(iterations) {
this.iterations = iterations;
},
/**
* Set log to true to show console log outputs.
* @param {Boolean} log
*/
setLog: function(log) {
this.log = log;
},
//@implement
_getIterationsToAdd: function() {
return this.iterations;
}
/**
* @method getReport
* Returns the time info for functions the
* run, they are keyed off by function name. The time
* info will may vary slightly from the console.time output.
* @return {Object}
*/
};
Vlug.utils.mix(Vlug.Runner.prototype, Vlug.mixins.TimeTracker);
/**
* @class Vlug.Interceptor
* Intercepts methods on objects to add time info, console logs or functions.
var interceptor = new Vlug.Interceptor({
logs: {
obj: Vlug.Runner.prototype,
fnName: 'run',
before: 'running ...',
after: function(f) {
return 'first call arg ' + f;
}
},
times: [{
obj: Vlug.Runner.prototype,
fnName: 'run'
}],
functions: {
obj: Vlug.Runner.prototype,
fnName: 'run',
before: function() {
window.alert('running ....')
}
}
}),
v = new Vlug.Runner({
log: false,
// .....
});
*v.run('a') would output something like
running ...
first call arg a
//This is from the times
run: 14.539ms
*interceptor.getReport() would output something like:
{ run:
{"iterationsRun":1,"totalTime":14.53899999614805,"average":14.53899999614805}
}
*after calling interceptor.restore()
* the methods will be restored back to their original states.
*/
Vlug.Interceptor = function(config) {
this.init(config);
};
Vlug.Interceptor.prototype = {
/**
* @cfg {{}| {}[]} logs
* An object or array of objects with the following properties
* @cfg logs.obj {Object} (required) the object that has the function to show logs.
* @cfg logs.fnName {String} (required) the name of the function to show logs.
* @cfg logs.before {String|Function} the console output to log before the function is called.
* @cfg logs.after {String|Function} the console output to log after the function is called.
* @cfg logs.logResult {Boolean} true to log the return value of the function.
*
*For example this would log <br>
*"running .." before run is called <br>
* and <br>
*"first call arg : undefined" <br>
*after run is called
@example
logs : {
fnName: 'run',
obj: Vlug.Runner.prototype,
before: 'running ...',
after: function() {
return 'first call arg' + arguments[0];
}
}
*/
/**
* @cfg {{}| {}[]} times
* An object or array of objects with the following properties
* @cfg times.obj {Object} (required) the object that has the function to track time.
* @cfg times.fnName {String} (required) the name of the function to track time.
* @cfg times.logResult {Boolean} true to log the return value of the function.
*/
/**
* @cfg {{}| {}[]} functions
* An object or array of objects with the following properties
* @cfg functions.obj {Object} (required) the object with the function to override.
* @cfg functions.fnName {String} (required) the name of the function.
* @cfg functions.before {Function} function to call before the original function has been called.
* @cfg functions.after {Function} function to call after the original function has been called.
* @cfg functions.logResult {Boolean} true to log the return value of the function.
*/
init: function(config) {
Vlug.utils.apply(this, Vlug.utils.apply(config, {log: true}));
this._restoreFns = [];
this._initLogs();
this._initTimeLogs();
this._initFunctions();
},
_initLogs: function() {
Vlug.utils.Array.each(this.logs, function(interceptConfig) {
this._intercept(this._createLogInterceptConfig(interceptConfig));
}, this);
},
_createLogInterceptConfig: function(c) {
var config = Vlug.utils.apply({}, c);
config.before = this._logToFn(config.before);
config.after = this._logToFn(config.after);
return config;
},
_logToFn: function(stringOrFn) {
if (typeof stringOrFn === 'function') {
return function() {
console.log(stringOrFn.apply(this, arguments));
};
} else if (typeof stringOrFn !== 'undefined') {
return function() {
console.log(stringOrFn);
};
}
return Vlug.emptyFn;
},
_initTimeLogs: function() {
Vlug.utils.Array.each(this.times, function(config, index, arr) {
var timeConfig = this._createTimeConfig(config, this._hasDuplicateName(config)
? config.fnName + index : config.fnName);
this._intercept(timeConfig);
}, this);
},
_hasDuplicateName: function(cfg) {
var i = 0,
arr = this.times,
len = arr.length,
name = cfg.fnName,
c;
for (; i < len; ++i) {
c = arr[i];
if (c !== cfg && c.fnName === name) {
return true;
}
}
},
_createTimeConfig: function(cfg, id) {
var me = this;
return Vlug.utils.apply(cfg, {
before: function() {
me.stampStart(id);
},
after: function() {
me.stampEnd(id);
}
});
},
_initFunctions: function() {
Vlug.utils.Array.each(this.functions, function(functionConfig) {
this._intercept(this._createFunctionInterceptConfig(functionConfig));
}, this);
},
_createFunctionInterceptConfig: function(c) {
var config = Vlug.utils.apply({}, c);
if (!config.before) {
config.before = Vlug.emptyFn;
}
if (!config.after) {
config.after = Vlug.emptyFn;
}
return config;
},
_intercept: function(interceptConfig) {
var object = interceptConfig.obj,
fnName = interceptConfig.fnName,
oldFn = object[fnName],
before = interceptConfig.before,
after = interceptConfig.after,
logResult = interceptConfig.logResult;
object[fnName] = function() {
var result;
before.apply(this, arguments);
result = oldFn.apply(this, arguments);
if (logResult) {
console.log(result);
}
after.apply(this, arguments);
return result;
};
this._restoreFns.push(function() {
object[fnName] = oldFn;
});
},
/**
* @method
* Restore the intercepted functions back to their original
* states.
*/
restore: function() {
Vlug.utils.Array.forEach(this._restoreFns.reverse(), function(fn) {
fn();
}, this);
},
//@implement
_getIterationsToAdd: function(id) {
return 1;
}
/**
* @method getReport
* Returns the time info for functions the
* run, they are keyed off by function name. The time
* info will may vary slightly from the console.time output.
* This will only show info if {@link Vlug.Interceptor#times times } are defined.
* @return {Object}
*/
};
Vlug.utils.mix(Vlug.Interceptor.prototype, Vlug.mixins.TimeTracker);
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = Vlug;
}
})();