/
utils.js
817 lines (773 loc) · 18.4 KB
/
utils.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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
"use strict";
var util = require('util');
var errors = require('./errors');
var utils = require('./utils');
/**
* Max int that can be accurately represented with 64-bit Number (2^53)
* @type {number}
* @const
*/
var maxInt = 9007199254740992;
function noop() {}
/**
* Creates a copy of a buffer
*/
function copyBuffer(buf) {
var targetBuffer = new Buffer(buf.length);
buf.copy(targetBuffer);
return targetBuffer;
}
/**
* Appends the original stack trace to the error after a tick of the event loop
*/
function fixStack(stackTrace, error) {
if (stackTrace) {
error.stack += '\n (event loop)\n' + stackTrace.substr(stackTrace.indexOf("\n") + 1);
}
return error;
}
/**
* Uses the logEmitter to emit log events
* @param {String} type
* @param {String} info
* @param [furtherInfo]
*/
function log(type, info, furtherInfo) {
if (!this.logEmitter) {
//noinspection JSUnresolvedVariable
if (!this.options || !this.options.logEmitter) {
throw new Error('Log emitter not defined');
}
//noinspection JSUnresolvedVariable
this.logEmitter = this.options.logEmitter;
}
this.logEmitter('log', type, this.constructor.name, info, furtherInfo || '');
}
/**
* Gets the sum of the length of the items of an array
*/
function totalLength (arr) {
if (arr.length === 1) {
return arr[0].length;
}
var total = 0;
arr.forEach(function (item) {
var length = item.length;
length = length ? length : 0;
total += length;
});
return total;
}
/**
* Merge the contents of two or more objects together into the first object. Similar to jQuery.extend
*/
function extend(target) {
var sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
if (!source) {
return;
}
var keys = Object.keys(source);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = source[key];
if (value === undefined) {
continue;
}
target[key] = value;
}
});
return target;
}
function lowerCaseExtend(target) {
var sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop.toLowerCase()] = source[prop];
}
}
});
return target;
}
/**
* Extends the target by the most inner props of sources
* @param {Object} target
* @returns {Object}
*/
function deepExtend(target) {
var sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
for (var prop in source) {
if (!source.hasOwnProperty(prop)) {
continue;
}
var targetProp = target[prop];
var targetType = (typeof targetProp);
//target prop is
// a native single type
// or not existent
// or is not an anonymous object (not class instance)
//noinspection JSUnresolvedVariable
if (!targetProp ||
targetType === 'number' ||
targetType === 'string' ||
util.isArray(targetProp) ||
util.isDate(targetProp) ||
targetProp.constructor.name !== 'Object'
) {
target[prop] = source[prop];
}
else {
//inner extend
target[prop] = deepExtend({}, targetProp, source[prop]);
}
}
});
return target;
}
function propCompare(propName) {
return function (a, b) {
if (a[propName] > b[propName])
return 1;
if (a[propName] < b[propName])
return -1;
return 0;
};
}
function funcCompare(name, argArray) {
return (function (a, b) {
if (typeof a[name] === 'undefined') {
return 0;
}
var valA = a[name].apply(a, argArray);
var valB = b[name].apply(b, argArray);
if (valA > valB)
return 1;
if (valA < valB)
return -1;
return 0;
});
}
/**
* Uses the iterator protocol to go through the items of the Array
* @param arr
* @returns {{next: function}}
*/
function arrayIterator (arr) {
var index = 0;
return { next : function () {
if (index >= arr.length) {
return {done: true};
}
return {value: arr[index++], done: false}
}};
}
/**
* Convert the iterator values into an array
* @param iterator
* @returns {Array}
*/
function iteratorToArray(iterator) {
var values = [];
var item = iterator.next();
while (!item.done) {
values.push(item.value);
item = iterator.next();
}
return values;
}
/**
* Searches the specified Array for the provided key using the binary
* search algorithm. The Array must be sorted.
* @param {Array} arr
* @param key
* @param {function} compareFunc
* @returns {number} The position of the key in the Array, if it is found.
* If it is not found, it returns a negative number which is the bitwise complement of the index of the first element that is larger than key.
*/
function binarySearch(arr, key, compareFunc) {
var low = 0;
var high = arr.length-1;
while (low <= high) {
var mid = (low + high) >>> 1;
var midVal = arr[mid];
var cmp = compareFunc(midVal, key);
if (cmp < 0) {
low = mid + 1;
}
else if (cmp > 0) {
high = mid - 1;
}
else
{
//The key was found in the Array
return mid;
}
}
return ~low; // key not found
}
/**
* Inserts the value in the position determined by its natural order determined by the compare func
* @param {Array} arr
* @param item
* @param {function} compareFunc
*/
function insertSorted(arr, item, compareFunc) {
if (arr.length === 0) {
return arr.push(item);
}
var position = binarySearch(arr, item, compareFunc);
if (position < 0) {
position = ~position;
}
arr.splice(position, 0, item);
}
/**
* Binds the domain (if any) to the callback
* @param {Function} callback
* @param {String} [name]
* @returns {Function}
*/
function bindDomain(callback, name) {
if (typeof callback !== 'function') {
throw new errors.ArgumentError(util.format('%s is not a function', name || 'callback'));
}
if (process.domain) {
callback = process.domain.bind(callback);
}
return callback;
}
/**
* Adapts the parameters based on the prepared metadata.
* If the params are passed as an associative array (Object),
* it adapts the object into an array with the same order as columns
* @param {Array|Object} params
* @param {Array} columns
* @returns {{ params: Array, keys: Object}} Returns an array of parameters and the keys as an associative array.
* @throws {Error} In case a parameter with a specific name is not defined
*/
function adaptNamedParamsPrepared(params, columns) {
if (!params || util.isArray(params) || !columns || columns.length === 0) {
//The parameters is an Array or there isn't parameter
return { params: params, keys: null};
}
var paramsArray = new Array(columns.length);
params = lowerCaseExtend({}, params);
var keys = {};
for (var i = 0; i < columns.length; i++) {
var name = columns[i].name;
if (!params.hasOwnProperty(name)) {
throw new errors.ArgumentError(util.format('Parameter "%s" not defined', name));
}
paramsArray[i] = params[name];
keys[name] = i;
}
return { params: paramsArray, keys: keys};
}
/**
* Adapts the associative-array of parameters and hints for simple statements
* into Arrays based on the (arbitrary) position of the keys.
* @param {Array|Object} params
* @param {QueryOptions} options
* @returns {{ params: Array.<{name, value}>, keys: Object}} Returns an array of parameters and the keys as an associative array.
*/
function adaptNamedParamsWithHints(params, options) {
if (!params || util.isArray(params)) {
//The parameters is an Array or there isn't parameter
return { params: params, keys: null};
}
options.namedParameters = true;
var keys = Object.keys(params);
var paramsArray = new Array(keys.length);
var hints = new Array(keys.length);
var userHints = options.hints || utils.emptyObject;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
//As lower cased identifiers
paramsArray[i] = { name: key.toLowerCase(), value: params[key]};
hints[i] = userHints[key];
}
options.hints = hints;
return { params: paramsArray, keys: keys};
}
/**
* Returns a string with a value repeated n times
* @param {String} val
* @param {Number} times
* @returns {String}
*/
function stringRepeat(val, times) {
if (!times || times < 0) {
return null;
}
if (times === 1) {
return val;
}
return new Array(times + 1).join(val);
}
/**
* Returns an array containing the values of the Object, similar to Object.values().
* If obj is null or undefined, it will return an empty array.
* @param {Object} obj
* @returns {Array}
*/
function objectValues(obj) {
if (!obj) {
return exports.emptyArray;
}
var keys = Object.keys(obj);
var values = new Array(keys.length);
for (var i = 0; i < keys.length; i++) {
values[i] = obj[keys[i]];
}
return values;
}
// Classes
/**
* Represents a unique set of values.
* @constructor
*/
function HashSet() {
this.length = 0;
this.items = {};
}
/**
* Adds a new item to the set.
* @param {Object} key
* @returns {boolean} Returns true if it was added to the set; false if the key is already present.
*/
HashSet.prototype.add = function (key) {
if (this.items[key]) {
return false;
}
this.items[key] = true;
this.length++;
return true;
};
/**
* @returns {boolean} Returns true if the key is present in the set.
*/
HashSet.prototype.contains = function (key) {
return this.items[key] === true;
};
/**
* Returns an array containing the set items.
* @returns {Array}
*/
HashSet.prototype.toArray = function () {
return Object.keys(this.items);
};
/**
* @param {Array} arr
* @param {Function} fn
* @param {Function} [callback]
*/
function each(arr, fn, callback) {
if (!Array.isArray(arr)) {
throw new TypeError('First parameter is not an Array');
}
callback = callback || noop;
var length = arr.length;
if (length === 0) {
return callback();
}
var completed = 0;
for (var i = 0; i < length; i++) {
fn(arr[i], next);
}
function next(err) {
if (err) {
var cb = callback;
callback = noop;
cb(err);
return;
}
if (++completed !== length) {
return;
}
callback();
}
}
/**
* @param {Array} arr
* @param {Function} fn
* @param {Function} [callback]
*/
function eachSeries(arr, fn, callback) {
if (!Array.isArray(arr)) {
throw new TypeError('First parameter is not an Array');
}
callback = callback || noop;
var length = arr.length;
if (length === 0) {
return callback();
}
var sync;
var index = 1;
fn(arr[0], next);
if (sync === undefined) {
sync = false;
}
function next(err) {
if (err) {
return callback(err);
}
if (index >= length) {
return callback();
}
if (sync === undefined) {
sync = true;
}
if (sync) {
return process.nextTick(function () {
fn(arr[index++], next);
});
}
fn(arr[index++], next);
}
}
/**
* @param {Array} arr
* @param {Function} fn
* @param {Function} [callback]
*/
function forEachOf(arr, fn, callback) {
return mapEach(arr, fn, true, callback);
}
/**
* @param {Array} arr
* @param {Function} fn
* @param {Function} [callback]
*/
function map(arr, fn, callback) {
return mapEach(arr, fn, false, callback);
}
function mapEach(arr, fn, useIndex, callback) {
if (!Array.isArray(arr)) {
throw new TypeError('First parameter must be an Array');
}
callback = callback || noop;
var length = arr.length;
if (length === 0) {
return callback(null, []);
}
var result = new Array(length);
var completed = 0;
var invoke = useIndex ? invokeWithIndex : invokeWithoutIndex;
for (var i = 0; i < length; i++) {
invoke(i);
}
function invokeWithoutIndex(i) {
fn(arr[i], function mapItemCallback(err, transformed) {
result[i] = transformed;
next(err);
});
}
function invokeWithIndex(i) {
fn(arr[i], i, function mapItemCallback(err, transformed) {
result[i] = transformed;
next(err);
});
}
function next(err) {
if (err) {
var cb = callback;
callback = noop;
cb(err);
return;
}
if (++completed !== length) {
return;
}
callback(null, result);
}
}
/**
* @param {Array} arr
* @param {Function} fn
* @param {Function} [callback]
*/
function mapSeries(arr, fn, callback) {
if (!Array.isArray(arr)) {
throw new TypeError('First parameter must be an Array');
}
callback = callback || noop;
var length = arr.length;
if (length === 0) {
return callback(null, []);
}
var result = new Array(length);
var index = 0;
var sync;
invoke(0);
if (sync === undefined) {
sync = false;
}
function invoke(i) {
fn(arr[i], function mapItemCallback(err, transformed) {
result[i] = transformed;
next(err);
});
}
function next(err) {
if (err) {
return callback(err);
}
if (++index === length) {
return callback(null, result);
}
if (sync === undefined) {
sync = true;
}
var i = index;
if (sync) {
return process.nextTick(function () {
invoke(i);
});
}
invoke(index);
}
}
/**
* @param {Array.<Function>} arr
* @param {Function} [callback]
*/
function parallel(arr, callback) {
if (!Array.isArray(arr)) {
throw new TypeError('First parameter must be an Array');
}
callback = callback || noop;
var length = arr.length;
var completed = 0;
for (var i = 0; i < length; i++) {
arr[i](next);
}
function next(err) {
if (err) {
var cb = callback;
callback = noop;
return cb(err);
}
if (++completed !== length) {
return;
}
callback();
}
}
/**
* Similar to async.series(), but instead accumulating the result in an Array, it callbacks with the result of the last
* function in the array.
* @param {Array.<Function>} arr
* @param {Function} [callback]
*/
function series(arr, callback) {
if (!Array.isArray(arr)) {
throw new TypeError('First parameter must be an Array');
}
callback = callback || noop;
var index = 0;
var sync;
next();
function next(err, result) {
if (err) {
return callback(err);
}
if (index === arr.length) {
return callback(null, result);
}
if (sync) {
return process.nextTick(function () {
//noinspection JSUnusedAssignment
sync = true;
arr[index++](next);
sync = false;
});
}
sync = true;
arr[index++](next);
sync = false;
}
}
/**
* @param {Number} count
* @param {Function} iteratorFunc
* @param {Function} [callback]
*/
function times(count, iteratorFunc, callback) {
callback = callback || noop;
count = +count;
if (isNaN(count) || count === 0) {
return callback();
}
var completed = 0;
for (var i = 0; i < count; i++) {
iteratorFunc(i, next);
}
function next(err) {
if (err) {
var cb = callback;
callback = noop;
return cb(err);
}
if (++completed !== count) {
return;
}
callback();
}
}
/**
* @param {Number} count
* @param {Number} limit
* @param {Function} iteratorFunc
* @param {Function} [callback]
*/
function timesLimit(count, limit, iteratorFunc, callback) {
callback = callback || noop;
limit = Math.min(limit, count);
var index = limit - 1;
var i;
var completed = 0;
for (i = 0; i < limit; i++) {
iteratorFunc(i, next);
}
i = -1;
var sync = undefined;
function next(err) {
if (err) {
var cb = callback;
callback = noop;
cb(err);
return;
}
if (++completed === count) {
return callback();
}
index++;
if (index >= count) {
return;
}
if (sync === undefined) {
sync = (i >= 0);
}
if (sync) {
var captureIndex = index;
return process.nextTick(function () {
iteratorFunc(captureIndex, next);
});
}
iteratorFunc(index, next);
}
}
/**
* @param {Number} count
* @param {Function} iteratorFunction
* @param {Function} callback
*/
function timesSeries(count, iteratorFunction, callback) {
count = +count;
if (isNaN(count) || count < 1) {
return callback();
}
var index = 1;
var sync;
iteratorFunction(0, next);
if (sync === undefined) {
sync = false;
}
function next(err) {
if (err) {
return callback(err);
}
if (index === count) {
return callback();
}
if (sync === undefined) {
sync = true;
}
var i = index++;
if (sync) {
//Prevent "Maximum call stack size exceeded"
return process.nextTick(function () {
iteratorFunction(i, next);
});
}
//do a sync call as the callback is going to call on a future tick
iteratorFunction(i, next);
}
}
/**
* @param {Function} condition
* @param {Function} fn
* @param {Function} callback
*/
function whilst(condition, fn, callback) {
var sync = 0;
next();
function next(err) {
if (err) {
return callback(err);
}
if (!condition()) {
return callback();
}
if (sync === 0) {
sync = 1;
fn(function (err) {
if (sync === 1) {
//sync function
sync = 4;
}
next(err);
});
if (sync === 1) {
//async function
sync = 2;
}
return;
}
if (sync === 4) {
//Prevent "Maximum call stack size exceeded"
return process.nextTick(function () {
fn(next);
});
}
//do a sync call as the callback is going to call on a future tick
fn(next);
}
}
exports.adaptNamedParamsPrepared = adaptNamedParamsPrepared;
exports.adaptNamedParamsWithHints = adaptNamedParamsWithHints;
exports.arrayIterator = arrayIterator;
exports.binarySearch = binarySearch;
exports.bindDomain = bindDomain;
exports.copyBuffer = copyBuffer;
exports.deepExtend = deepExtend;
exports.each = each;
exports.eachSeries = eachSeries;
/** @const */
exports.emptyArray = Object.freeze([]);
/** @const */
exports.emptyObject = Object.freeze({});
exports.extend = extend;
exports.fixStack = fixStack;
exports.forEachOf = forEachOf;
exports.funcCompare = funcCompare;
exports.insertSorted = insertSorted;
exports.iteratorToArray = iteratorToArray;
exports.log = log;
exports.map = map;
exports.mapSeries = mapSeries;
exports.maxInt = maxInt;
exports.noop = noop;
exports.objectValues = objectValues;
exports.parallel = parallel;
exports.propCompare = propCompare;
exports.series = series;
exports.stringRepeat = stringRepeat;
exports.times = times;
exports.timesLimit = timesLimit;
exports.timesSeries = timesSeries;
exports.totalLength = totalLength;
exports.whilst = whilst;
exports.HashSet = HashSet;