forked from datastax/nodejs-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
1087 lines (1001 loc) · 25.1 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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const util = require('util');
const net = require('net');
const { EventEmitter } = require('events');
const errors = require('./errors');
const promiseUtils = require('./promise-utils');
/**
* Max int that can be accurately represented with 64-bit Number (2^53)
* @type {number}
* @const
*/
const maxInt = 9007199254740992;
const maxInt32 = 0x7fffffff;
const emptyObject = Object.freeze({});
const emptyArray = Object.freeze([]);
function noop() {}
/**
* Forward-compatible allocation of buffer, filled with zeros.
* @type {Function}
*/
const allocBuffer = Buffer.alloc || allocBufferFillDeprecated;
/**
* Forward-compatible unsafe allocation of buffer.
* @type {Function}
*/
const allocBufferUnsafe = Buffer.allocUnsafe || allocBufferDeprecated;
/**
* Forward-compatible allocation of buffer to contain a string.
* @type {Function}
*/
const allocBufferFromString = (Int8Array.from !== Buffer.from && Buffer.from) || allocBufferFromStringDeprecated;
/**
* Forward-compatible allocation of buffer from an array of bytes
* @type {Function}
*/
const allocBufferFromArray = (Int8Array.from !== Buffer.from && Buffer.from) || allocBufferFromArrayDeprecated;
function allocBufferDeprecated(size) {
// eslint-disable-next-line
return new Buffer(size);
}
function allocBufferFillDeprecated(size) {
const b = allocBufferDeprecated(size);
b.fill(0);
return b;
}
function allocBufferFromStringDeprecated(text, encoding) {
if (typeof text !== 'string') {
throw new TypeError('Expected string, obtained ' + util.inspect(text));
}
// eslint-disable-next-line
return new Buffer(text, encoding);
}
function allocBufferFromArrayDeprecated(arr) {
if (!Array.isArray(arr)) {
throw new TypeError('Expected Array, obtained ' + util.inspect(arr));
}
// eslint-disable-next-line
return new Buffer(arr);
}
/**
* @returns {Function} Returns a wrapper function that invokes the underlying callback only once.
* @param {Function} callback
*/
function callbackOnce(callback) {
let cb = callback;
return (function wrapperCallback(err, result) {
cb(err, result);
cb = noop;
});
}
/**
* Creates a copy of a buffer
*/
function copyBuffer(buf) {
const targetBuffer = allocBufferUnsafe(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, options) {
if (!this.logEmitter) {
const effectiveOptions = options || this.options;
if (!effectiveOptions || !effectiveOptions.logEmitter) {
throw new Error('Log emitter not defined');
}
this.logEmitter = effectiveOptions.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;
}
let total = 0;
arr.forEach(function (item) {
let 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 / Object.assign.
* The main difference between this method is that declared properties with an <code>undefined</code> value are not set
* to the target.
*/
function extend(target) {
const sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
if (!source) {
return;
}
const keys = Object.keys(source);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = source[key];
if (value === undefined) {
continue;
}
target[key] = value;
}
});
return target;
}
/**
* Returns a new object with the property names set to lowercase.
*/
function toLowerCaseProperties(obj) {
const keys = Object.keys(obj);
const result = {};
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
result[k.toLowerCase()] = obj[k];
}
return result;
}
/**
* Extends the target by the most inner props of sources
* @param {Object} target
* @returns {Object}
*/
function deepExtend(target) {
const sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
for (const prop in source) {
// eslint-disable-next-line no-prototype-builtins
if (!source.hasOwnProperty(prop)) {
continue;
}
const targetProp = target[prop];
const targetType = (typeof targetProp);
//target prop is
// a native single type
// or not existent
// or is not an anonymous object (not class instance)
if (!targetProp ||
targetType === 'number' ||
targetType === 'string' ||
Array.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;
}
const valA = a[name].apply(a, argArray);
const 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 {Array} arr
* @returns {Iterator}
*/
function arrayIterator (arr) {
return arr[Symbol.iterator]();
}
/**
* Convert the iterator values into an array
* @param iterator
* @returns {Array}
*/
function iteratorToArray(iterator) {
const values = [];
let 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) {
let low = 0;
let high = arr.length-1;
while (low <= high) {
const mid = (low + high) >>> 1;
const midVal = arr[mid];
const 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;
}
}
// key not found
return ~low;
}
/**
* 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);
}
let position = binarySearch(arr, item, compareFunc);
if (position < 0) {
position = ~position;
}
arr.splice(position, 0, item);
}
/**
* Validates the provided parameter is of type function.
* @param {Function} fn The instance to validate.
* @param {String} [name] Name of the function to use in the error message. Defaults to 'callback'.
* @returns {Function}
*/
function validateFn(fn, name) {
if (typeof fn !== 'function') {
throw new errors.ArgumentError(util.format('%s is not a function', name || 'callback'));
}
return fn;
}
/**
* 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 {Array} Returns an array of parameters.
* @throws {Error} In case a parameter with a specific name is not defined
*/
function adaptNamedParamsPrepared(params, columns) {
if (!params || Array.isArray(params) || !columns || columns.length === 0) {
// params is an array or there aren't parameters
return params;
}
const paramsArray = new Array(columns.length);
params = toLowerCaseProperties(params);
const keys = {};
for (let i = 0; i < columns.length; i++) {
const name = columns[i].name;
// eslint-disable-next-line no-prototype-builtins
if (!params.hasOwnProperty(name)) {
throw new errors.ArgumentError(util.format('Parameter "%s" not defined', name));
}
paramsArray[i] = params[name];
keys[name] = i;
}
return paramsArray;
}
/**
* 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 {ExecutionOptions} execOptions
* @returns {{ params: Array<{name, value}>, namedParameters: boolean, keyIndexes: object }} Returns an array of
* parameters and the keys as an associative array.
*/
function adaptNamedParamsWithHints(params, execOptions) {
if (!params || Array.isArray(params)) {
//The parameters is an Array or there isn't parameter
return { params: params, namedParameters: false, keyIndexes: null };
}
const keys = Object.keys(params);
const paramsArray = new Array(keys.length);
const hints = new Array(keys.length);
const userHints = execOptions.getHints() || emptyObject;
const keyIndexes = {};
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
// As lower cased identifiers
paramsArray[i] = { name: key.toLowerCase(), value: params[key]};
hints[i] = userHints[key];
keyIndexes[key] = i;
}
execOptions.setHints(hints);
return { params: paramsArray, namedParameters: true, keyIndexes };
}
/**
* 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 emptyArray;
}
const keys = Object.keys(obj);
const values = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
values[i] = obj[keys[i]];
}
return values;
}
/**
* Wraps the callback-based method. When no originalCallback is not defined, it returns a Promise.
* @param {ClientOptions} options
* @param {Function} originalCallback
* @param {Function} handler
* @returns {Promise|undefined}
*/
function promiseWrapper(options, originalCallback, handler) {
if (typeof originalCallback === 'function') {
// Callback-based invocation
handler.call(this, originalCallback);
return undefined;
}
const factory = options.promiseFactory || defaultPromiseFactory;
const self = this;
return factory(function handlerWrapper(callback) {
handler.call(self, callback);
});
}
/**
* @param {Function} handler
* @returns {Promise}
*/
function defaultPromiseFactory(handler) {
return new Promise(function executor(resolve, reject) {
handler(function handlerCallback(err, result) {
if (err) {
return reject(err);
}
resolve(result);
});
});
}
/**
* Returns the first not undefined param
*/
function ifUndefined(v1, v2) {
return v1 !== undefined ? v1 : v2;
}
/**
* Returns the first not undefined param
*/
function ifUndefined3(v1, v2, v3) {
if (v1 !== undefined) {
return v1;
}
return v2 !== undefined ? v2 : v3;
}
/**
* Shuffles an Array in-place.
* @param {Array} arr
* @returns {Array}
* @private
*/
function shuffleArray(arr) {
// Fisher–Yates algorithm
for (let i = arr.length - 1; i > 0; i--) {
// Math.random() has an extremely short permutation cycle length but we don't care about collisions
const j = Math.floor(Math.random() * (i + 1));
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
// 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.contains(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.length > 0 && this.items[key] === true;
};
/**
* Removes the item from set.
* @param key
* @return {boolean} Returns true if the key existed and was removed, otherwise it returns false.
*/
HashSet.prototype.remove = function (key) {
if (!this.contains(key)) {
return false;
}
delete this.items[key];
this.length--;
};
/**
* Returns an array containing the set items.
* @returns {Array}
*/
HashSet.prototype.toArray = function () {
return Object.keys(this.items);
};
/**
* Utility class that resolves host names into addresses.
*/
class AddressResolver {
/**
* Creates a new instance of the resolver.
* @param {Object} options
* @param {String} options.nameOrIp
* @param {Object} [options.dns]
*/
constructor(options) {
if (!options || !options.nameOrIp || !options.dns) {
throw new Error('nameOrIp and dns lib must be provided as part of the options');
}
this._resolve4 = util.promisify(options.dns.resolve4);
this._nameOrIp = options.nameOrIp;
this._isIp = net.isIP(options.nameOrIp);
this._index = 0;
this._addresses = null;
this._refreshing = null;
}
/**
* Resolves the addresses for the host name.
*/
async init() {
if (this._isIp) {
return;
}
await this._resolve();
}
/**
* Tries to resolve the addresses for the host name.
*/
async refresh() {
if (this._isIp) {
return;
}
if (this._refreshing) {
return await promiseUtils.fromEvent(this._refreshing, 'finished');
}
this._refreshing = new EventEmitter().setMaxListeners(0);
try {
await this._resolve();
} catch (err) {
// Ignore the possible resolution error
}
this._refreshing.emit('finished');
this._refreshing = null;
}
async _resolve() {
const arr = await this._resolve4(this._nameOrIp);
if (!arr || arr.length === 0) {
throw new Error(`${this._nameOrIp} could not be resolved`);
}
this._addresses = arr;
}
/**
* Returns resolved ips in a round-robin fashion.
*/
getIp() {
if (this._isIp) {
return this._nameOrIp;
}
const item = this._addresses[this._index % this._addresses.length];
this._index = (this._index !== maxInt32) ? (this._index + 1) : 0;
return item;
}
}
/**
* @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;
const length = arr.length;
if (length === 0) {
return callback();
}
let completed = 0;
for (let i = 0; i < length; i++) {
fn(arr[i], next);
}
function next(err) {
if (err) {
const 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;
const length = arr.length;
if (length === 0) {
return callback();
}
let sync;
let 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;
const length = arr.length;
if (length === 0) {
return callback(null, []);
}
const result = new Array(length);
let completed = 0;
const invoke = useIndex ? invokeWithIndex : invokeWithoutIndex;
for (let 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) {
const 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;
const length = arr.length;
if (length === 0) {
return callback(null, []);
}
const result = new Array(length);
let index = 0;
let 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;
}
const 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;
const length = arr.length;
let completed = 0;
for (let i = 0; i < length; i++) {
arr[i](next);
}
function next(err) {
if (err) {
const 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;
let index = 0;
let 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 () {
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();
}
let completed = 0;
for (let i = 0; i < count; i++) {
iteratorFunc(i, next);
}
function next(err) {
if (err) {
const 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) {
let sync = undefined;
callback = callback || noop;
limit = Math.min(limit, count);
let index = limit - 1;
let i;
let completed = 0;
for (i = 0; i < limit; i++) {
iteratorFunc(i, next);
}
i = -1;
function next(err) {
if (err) {
const 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) {
const 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();
}
let index = 1;
let 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;
}
const 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);
}
}