-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
1625 lines (1268 loc) · 39.5 KB
/
index.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
'use strict';
const
async = require('async'),
crypto = require('crypto'),
fs = require('fs'),
os = require('os'),
precon = require('@mintpond/mint-precon'),
passwords = require('./libs/service.passwords');
const DATE = new Date();
const BIT_UNITS = ['b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'];
const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
const HASH_UNITS = ['h', 'Kh', 'Mh', 'Gh', 'Th', 'Ph'];
const TIME_UNITS = ['secs', 'mins', 'hrs'];
const mu = module.exports = {
get STRONG_PASSWORD_CHARS() { return passwords.STRONG_PASSWORD_CHARS },
get ALPHA_NUMERIC_CHARS() { return passwords.ALPHA_NUMERIC_CHARS },
get BASE58_READABLE_CHARS() { return passwords.BASE58_READABLE_CHARS },
get HEX_CHARS() { return passwords.HEX_CHARS },
// Classes
AdaptiveConfig: require('./libs/class.AdaptiveConfig'),
AliasMap: require('./libs/class.AliasMap'),
CallbackBuffer: require('./libs/class.CallbackBuffer'),
Counter: require('./libs/class.Counter'),
DirtyData: require('./libs/class.DirtyData'),
EntryCounter: require('./libs/class.EntryCounter'),
HighLowAverage: require('./libs/class.HighLowAverage'),
SimpleRingBuffer: require('./libs/class.SimpleRingBuffer'),
StopWatch: require('./libs/class.StopWatch'),
Timeouts: require('./libs/class.Timeouts'),
TTLMemCache: require('./libs/class.TTLMemCache'),
WorkTracker: require('./libs/class.WorkTracker'),
// Services
/**
* BigInt conversion utilities.
*/
bi: require('./libs/service.bi'),
/**
* Buffer builder and manipulation utilities.
*/
buffers: require('./libs/service.buffers'),
/**
* Password hashing and matching utilities.
*/
passwords: passwords,
/**
* Javascript Prototype utilities.
*/
prototypes: require('./libs/service.prototypes'),
// Functions
/**
* Async each function. Exceptions in iterator are caught and returned as an error.
*
* @returns {function}
*/
each: each,
/**
* Async eachSeries function. Exceptions in iterator are caught and returned as an error.
*
* @returns {function}
*/
eachSeries: eachSeries,
/**
* Async eachLimit function. Exceptions in iterator are caught and returned as an error.
*
* @returns {function}
*/
eachLimit: eachLimit,
/**
* Async parallel function. Exceptions in functions are caught and returned as an error.
*
* @returns {function}
*/
parallel: parallel,
/**
* Async series function. Exceptions in functions are caught and returned as an error.
*
* @returns {function}
*/
series: series,
/**
* Async some function.
*
* @returns {function}
*/
some: some,
/**
* Async waterfall function. Exceptions in functions are caught and returned as an error.
*
* @returns {function}
*/
waterfall: waterfall,
/**
* Determine if a value is an object.
*
* @param val {*}
* @returns {boolean}
*/
isObject: val => typeof val === 'object',
/**
* Determine if a value is a function.
*
* @param val {*}
* @returns {boolean}
*/
isFunction: val => typeof val === 'function',
/**
* Determine if a value is a boolean.
*
* @param val {*}
* @returns {boolean}
*/
isBoolean: val => typeof val === 'boolean',
/**
* Determine if a value is a string.
*
* @param val {*}
* @returns {boolean}
*/
isString: val => typeof val === 'string',
/**
* Determine if a value is a non-empty string
*
* @param val {*}
* @returns {boolean}
*/
isFilledString: val => typeof val === 'string' && !!val,
/**
* Determine if a value is a number.
*
* @param val {*}
* @returns {boolean}
*/
isNumber: val => typeof val === 'number',
/**
* Determine if a value is a BigInt.
*
* @param val {*}
* @returns {boolean}
*/
isBigInt: val => typeof val === 'bigint',
/**
* Determine if a value is an integer.
*
* @param val {*}
* @returns {boolean}
*/
isInteger: val => typeof val === 'number' && Number.isInteger(val),
/**
* Determine if a value is undefined.
*
* @param val {*}
* @returns {boolean}
*/
isUndefined: val => typeof val === 'undefined',
/**
* Determine if a value is defined.
*
* @param val {*}
* @returns {boolean}
*/
isDefined: val => typeof val !== 'undefined',
/**
* Determine if a value is null.
*
* @param val {*}
* @returns {boolean}
*/
isNull: val => val === null,
/**
* Determine if a value is null or undefined.
*
* @param val {*}
* @returns {boolean}
*/
isNotSet: val => val === null || typeof val === 'undefined',
/**
* Determine if a value is an Array.
*
* @param val {*}
* @returns {boolean}
*/
isArray: val => Array.isArray(val),
/**
* Throw an exception or, if available, put the error as the first argument of a callback.
*
* @param message {string|Error}
* @param [callback] {function(err:Error)}
*/
throw: throwFn,
/**
* Create an array containing evenly sized chunks (arrays) of an input array.
*
* The final chunk in the result may be smaller if the chunks cannot be divided evenly.
*
* @param array {*[]} The array to split into chunks.
* @param size {number} The number of elements in each chunk.
* @returns {*[]} An array of array chunks.
*/
chunk: chunk,
/**
* Concat multiple arrays or iterables in to a single array.
*
* @param arrays {*[]|IterableIterator}
* @returns {*[]}
*/
concat: concat,
/**
* Return elements in array that are not found in the provided exclusion array.
*
* @param array {*[]}
* @param excludeArr {*[]}
* @param [comparatorFn] {function(a:*, b:*):boolean}
* @returns {*[]}
*/
difference: difference,
/**
* Push all elements of the specified source array into the target array.
*
* @param targetArr {*[]} The array to push into.
* @param sourceArrs {*[]} Arrays whose elements should be pushed into the target array.
* @returns {*[]} The target array
*/
pushAll: pushAll,
/**
* Covert 1 or more arrays and/or IterableIterator's into a Set.
*
* @param arrays {*[]|IterableIterator<*>}
* @returns {Set<*>}
*/
toSet: toSet,
/**
* Sort an array in ascending order.
*
* @param array {*[]} The array to sort.
* @param [propOrFn] {string|function(elem:*):*} The name of the property in elements to sort by or a function to
* return the value to sort by of an element.
*/
sortAscending: sortAscending,
/**
* Sort an array in descending order.
*
* @param array {*[]} The array to sort.
* @param [propOrFn] {string|number|function(elem:*):*} The name of the property in elements to sort by,
* or the index position in array elements to sort by, or a function to return the value to sort by from an element.
*/
sortDescending: sortDescending,
/**
* Read a string for the path of an inline file and return the contents of the file as a string. If the str
* argument is not an inline file path or the file cannot be read then the value passed into the str parameter
* is returned.
*
* Example of an inline file path: "file:../path/to/file.name"
*
* A valid inline file path must begin with the prefix "file:" with the rest of the string being the path to
* the file.
*
* @param str {string|*}
* @param [ext] {string} A filename extension to try if the file is not found (include preceding period).
* @param [callback] {function(err:*,result:string|*)} Callback for async operation. Exclude for a sync operation.
* @returns {string|*|undefined} Returns result when the operation is synchronous. No result returned for async.
*/
getInlineFile: getInlineFile,
/**
* Find and replace all inline file strings in an object with contents of the specified file if found.
*
* @param obj {object}
* @param [callback] {function(err:*, obj:object)}
*/
inlineAllFiles: inlineAllFiles,
/**
* Get the epoch time in seconds.
*
* @returns {number}
*/
now: now,
/**
* Get the epoch time in milliseconds.
*
* @returns {number}
*/
nowMs: nowMs,
/**
* Determine if an epoch time is in milliseconds.
*
* @param time {number} The epoch time to check.
* @returns {boolean} True if milliseconds, false if seconds.
*/
isTimeInMs: isTimeInMs,
/**
* Truncate epoch time seconds by minute.
*
* @param [time=now] {number} The time to truncate. Uses current time if not specified.
* @returns {number}
*/
truncTimeMinute: truncTimeMinute,
/**
* Get the start time (epoch seconds) of the day of the specified time (epoch seconds or milliseconds).
*
* @param [time=now] {number} The time in epoch seconds or milliseconds.
* @param [offsetDays=0] {number} The number of days to offset the result.
* @returns {number}
*/
getDayStartTime: getDayStartTime,
/**
* Get the end time (epoch seconds) of the day of the specified time (epoch seconds or milliseconds).
*
* @param [time=now] {number} The time in epoch seconds or milliseconds.
* @param [offsetDays=0] {number} The number of days to offset the result.
* @returns {number}
*/
getDayEndTime: getDayEndTime,
/**
* Get the start time (epoch seconds) of the week of the specified time (epoch seconds or milliseconds)
*
* The start of the week is Sunday at 12:00:00 AM UTC
*
* @param [time=now] {number} The time in epoch seconds or milliseconds.
* @param [weekOffset=0] {number} The number of weeks to offset the result.
* @returns {number}
*/
getWeekStartTime: getWeekStartTime,
/**
* Get the end time (epoch seconds) of the week of the specified time (epoch seconds or milliseconds)
*
* The end of the week is Saturday at 11:59:59 PM UTC
*
* @param [time=now] {number} The time in epoch seconds or milliseconds.
* @param [weekOffset=0] {number} The number of weeks to offset the result.
* @returns {number}
*/
getWeekEndTime: getWeekEndTime,
/**
* Get the start time (epoch seconds) of the month of the specified time (epoch seconds or milliseconds)
*
* @param [time=now] {number} The time in epoch seconds or milliseconds.
* @param [monthOffset=0] {number} The number of months to offset the result.
* @returns {number}
*/
getMonthStartTime: getMonthStartTime,
/**
* Get the end time (epoch seconds) of the month of the specified time (epoch seconds or milliseconds)
*
* @param [time=now] {number} The time in epoch seconds or milliseconds.
* @param [monthOffset=0] {number} The number of months to offset the result.
* @returns {number}
*/
getMonthEndTime: getMonthEndTime,
/**
* Convert timestamp (epoch seconds) to a string in local form: '2020-04-24'
*
* @param [time=now] {number}
* @returns {string}
*/
getW3CDateString: getW3CDateString,
/**
* Convert timestamp (epoch seconds) to a string in UTC form: '2020-04-24'
*
* @param [time=now] {number}
* @returns {string}
*/
getW3CDateUtcString: getW3CDateUtcString,
/**
* Convert timestamp (epoch seconds) to a string in local form: '2020-04-24T13:22:01-07:30'
*
* @param [time=now] {number}
* @returns {string}
*/
getW3CDateTimeString: getW3CDateTimeString,
/**
* Convert timestamp (epoch seconds) to a string in UTC form: '2020-04-24T13:22:01+00:00'
*
* @param [time=now] {number}
* @returns {string}
*/
getW3CDateTimeUtcString: getW3CDateTimeUtcString,
/**
* Get hours, minutes, and sign components of a timezone offset in minutes.
*
* @param offsetMin {number}
* @returns {{hours: number, minutes: number, sign: string}}
*/
getTimeZoneOffsetComponents: getTimeZoneOffsetComponents,
/**
* Get a Year-Month-Date string in local time using optional custom separator.
*
* Using default separator, output takes the form '2020_04_24'
*
* @param dateTime {Date|number}
* @param [separator='_'] {string}
* @returns {string}
*/
getYmdString: getYmdString,
/**
* Get a Year-Month-Date string in UTC time using optional custom separator.
*
* Using default separator, output takes the form '2020_04_24'
*
* @param dateTime {Date|number}
* @param [separator='_'] {string}
* @returns {string}
*/
getUtcYmdString: getUtcYmdString,
/**
* Convert a number to string and prefix with 0's so that it is at least a minimum number of digits long.
* Decimal places are ignored.
*
* @param number {string|number}
* @param minLen {number}
* @returns {string}
*/
padNum: padNum,
/**
* Convert a number to string and prefix with 0's so that it is at least 2 digits long.
* Decimal places are ignored.
*
* @param number {string|number}
* @returns {string}
*/
padNum2: padNum2,
/**
* Simple formatter for bit unit values. Finds the largest unit to display value for readability.
*
* @param bytes {number} The number of bytes
* @param [decimalPlaces=2] The number of decimal places to use.
* @returns {{number: string, units: string, toJSON(): string, toString(): string}}
*/
formatBits: formatBits,
/**
* Simple formatter for byte unit values. Finds the largest unit to display value for readability.
*
* @param bytes {number} The number of bytes
* @param [decimalPlaces=2] The number of decimal places to use.
* @returns {{number: string, units: string, toJSON(): string, toString(): string}}
*/
formatBytes: formatBytes,
/**
* Simple formatter for hash unit values. Finds the largest unit to display value for readability.
*
* @param hashes {number} The number of hashes.
* @param [decimalPlaces=2] The number of decimal places to use.
* @returns {{number: string, units: string, toJSON(): string, toString(): string}}
*/
formatHashes: formatHashes,
/**
* Simple formatter for seconds unit values. Finds the largest unit to display value for readability.
*
* @param seconds {number} The number of seconds.
* @param [decimalPlaces=2] The number of decimal places to use.
* @returns {{number: string, units: string, toJSON(): string, toString(): string}}
*/
formatSeconds: formatSeconds,
/**
* Customizable number formatter used to make large numbers more readable by using larger units.
*
* @param num {number} The number in the smallest unit scale.
* @param [decimalPlaces=2] {number} The number of decimal places in the result number.
* @param unitNamesArr {string[]} An array of unit names from smallest unit to largest unit.
* @param divArr {number|number[]} The division of units. Can be a single number or an array of divisions for each
* unit scale.
* @returns {{number:string, units:string, toJSON():string, toString():string}}
*/
formatUnits: formatUnits,
/**
* Replace char in string at specified index with a replacement string.
*
* @param str
* @param index
* @param replacement
* @returns {string}
*/
replaceCharAt: replaceCharAt,
/**
* Parse string for instances of Javascript escaped characters (i.e "\\n") and convert to character.
*
* Handles new-line (\n), carriage return (\n), and tab (\t)
*
* @param str {string}
* @returns {string}
*/
parseJsEscapes: parseJsEscapes,
/**
* Determine if a number is a power of 2.
*
* @param num {number}
* @returns {boolean}
*/
isPowerOf2: isPowerOf2,
/**
* Parse hex value to number.
*
* @param hex {string}
* @returns {number}
*/
parseHex: parseHex,
/**
* Parse hex value to BigInt.
*
* @param hex {string}
* @returns {BigInt}
*/
parseHexToBi: parseHexToBi,
/**
* Expand number of bytes in a big endian hex value.
* A "0x" prefix will be stripped.
* If the hex is larger than the specified size then the hex is returned without changing its byte size.
*
* @param hex {string}
* @param size {number} The number of bytes the hex should be.
* @returns {string}
*/
expandHex: expandHex,
/**
* Get a pseudo random integer (fast random).
*
* @param min {number} The minimum acceptable value.
* @param max {number} The maximum acceptable value.
* @returns {number}
*/
randInteger: randInteger,
/**
* Get a cryptographically strong random integer.
*
* @param min {number} The minimum acceptable value.
* @param max {number} The maximum acceptable value.
* @returns {number}
*/
cryptoRandInteger: cryptoRandInteger,
/**
* Get a pseudo random number (fast random).
*
* @param min {number} The minimum acceptable value.
* @param max {number} The maximum acceptable value.
* @returns {number}
*/
randNumber: randNumber,
/**
* Get a cryptographically strong random number.
*
* @param min {number} The minimum acceptable value.
* @param max {number} The maximum acceptable value.
* @returns {number}
*/
cryptoRandNumber: cryptoRandNumber,
/**
* Generate a string of pseudo random characters (fast random).
*
* @param length {number} The number of characters to generate.
* @param [chars] {string} The whitelist of valid characters. Default is BASE58_READABLE_CHARS
*
* @returns {string}
*/
randChars: randChars,
/**
* Generate a string of cryptographically strong random characters.
*
* @param length {number} The number of characters to generate.
* @param [chars] {string} The whitelist of valid characters. Default is BASE58_READABLE_CHARS
*
* @returns {string}
*/
cryptoRandChars: cryptoRandChars,
/**
* Get an array of the local machines IPv4 addresses.
*
* @returns {string[]}
*/
getIPv4Arr: getIPv4Arr,
/**
* Get an array of the local machines IPv6 addresses.
*
* @returns {string[]}
*/
getIPv6Arr: getIPv6Arr,
/**
* Get local machine IP address.
*
* @returns {string|null}
*/
getIPv4: getIPv4,
/**
* Get local machine IP address.
*
* @returns {string|null}
*/
getIPv6: getIPv6
};
function each(arr, iteratorFn, callback) {
iteratorFn = _wrapAsyncFn(iteratorFn);
async.each(arr, iteratorFn, callback);
}
function eachSeries(arr, iteratorFn, callback) {
iteratorFn = _wrapAsyncFn(iteratorFn);
async.eachSeries(arr, iteratorFn, callback);
}
function eachLimit(arr, limit, iteratorFn, callback) {
iteratorFn = _wrapAsyncFn(iteratorFn);
async.eachLimit(arr, limit, iteratorFn, callback);
}
function parallel(fnArr, callback) {
fnArr = fnArr.map(_wrapAsyncFn);
async.parallel(fnArr, callback);
}
function series(fnArr, callback) {
fnArr = fnArr.map(_wrapAsyncFn);
async.series(fnArr, callback);
}
function some(arr, iteratorFn, callback) {
async.some(arr, iteratorFn, callback);
}
function waterfall(fnArr, callback) {
fnArr = fnArr.map(_wrapAsyncFn);
async.waterfall(fnArr, callback);
}
function throwFn(message, callback) {
precon.opt_funct(callback, 'callback');
let error;
if (typeof message === 'string') {
error = new Error(message);
}
else if (message instanceof Error) {
error = message;
}
else if (typeof message === 'object') {
if (message.toJSON) {
message = message.toJSON();
}
error = new Error(message.toString());
Object.keys(message).forEach(key => {
error[key] = message[key];
});
}
else {
error = new Error('unspecified error');
}
if (callback) {
setImmediate(callback.bind(null, error));
}
else {
throw error;
}
}
function chunk(array, size) {
precon.opt_array(array, 'array');
precon.opt_number(size, 'size');
if (!array || !array.length)
return [];
size = size || 1;
let index = 0,
resIndex = 0,
result = Array(Math.ceil(array.length / size));
while (index < array.length) {
result[resIndex++] = array.slice(index, index += size);
}
return result;
}
function concat(...arrays) {
for (let i = 0; i < arrays.length; i++) {
if (!Array.isArray(arrays[i]))
arrays[i] = Array.from(arrays[i]);
}
return [].concat(...arrays);
}
function difference(array, excludeArr, comparatorFn) {
precon.array(array, 'array');
precon.array(excludeArr, 'excludeArr');
precon.opt_funct(comparatorFn, 'comparatorFn');
let index = 0;
const resultArr = [];
if (!array.length)
return resultArr;
if (!comparatorFn) {
comparatorFn = (a, b) => {
return a === b;
};
}
start:
while (index < array.length) {
const value = array[index];
index++;
let excludeIndex = excludeArr.length;
while (excludeIndex--) {
if (comparatorFn(excludeArr[excludeIndex], value))
continue start;
}
resultArr.push(value);
}
return resultArr;
}
function pushAll(targetArr, ...sourceArrs) {
precon.array(targetArr, 'targetArray');
sourceArrs.forEach(array => {
targetArr.push.apply(targetArr, array);
});
return targetArr;
}
function toSet(...arrays) {
const set = new Set();
arrays.forEach(array => {
if (!Array.isArray(array))
array = Array.from(array);
array.forEach(element => {
set.add(element);
});
});
return set;
}
function sortAscending(array, propOrFn) {
precon.array(array, 'array');
let fn = propOrFn;
if (mu.isString(propOrFn) || mu.isNumber(propOrFn)) {
fn = element => {
return element[propOrFn];
}
}
array.sort((a, b) => {
const aValue = mu.isFunction(fn) ? fn(a) : a;
const bValue = mu.isFunction(fn) ? fn(b) : b;
if (!mu.isNumber(aValue) || !mu.isNumber(bValue)) {
if (aValue > bValue) return 1;
if (aValue < bValue) return -1;
return 0;
}
return aValue - bValue;
});
}
function sortDescending(array, propOrFn) {
precon.array(array, 'array');
let fn = propOrFn;
if (mu.isString(propOrFn) || mu.isNumber(propOrFn)) {
fn = element => {
return element[propOrFn];
}
}
array.sort((a, b) => {
const aValue = mu.isFunction(fn) ? fn(a) : a;
const bValue = mu.isFunction(fn) ? fn(b) : b;
if (!mu.isNumber(aValue) || !mu.isNumber(bValue)) {
if (aValue > bValue) return -1;
if (aValue < bValue) return 1;
return 0;
}
return bValue - aValue;
});
}
function getInlineFile(str, ext, callback) {
if (typeof callback === 'function') {
if (typeof str !== 'string' || !str.startsWith('file:')) {
setImmediate(callback.bind(null, null, str));
return;
}
const filePath = str.slice(5);
_readAsync(filePath, ext);
function _readAsync(filePath, ext) {
fs.readFile(filePath, 'utf8', (err, contents) => {
if (err) {
if (ext) {
_readAsync(filePath + ext);
}
else {
callback(err, str);
}
}
else {
callback(null, contents);
}
});
}
}
else {
if (typeof str !== 'string' || !str.startsWith('file:'))
return str;
const filePath = str.slice(5);
return _read(filePath, ext);
function _read(filePath, ext) {
let contents;
try {
contents = fs.readFileSync(filePath, 'utf8');
}
catch (err) {
if (ext) {
return _read(filePath + ext);
}
else {
return str;
}
}
return contents;
}
}
}
function inlineAllFiles(obj, callback) {
precon.obj(obj, 'obj');
precon.opt_funct(callback, 'callback');
const keys = Object.keys(obj);
if (!callback) {
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = obj[key];
if (mu.isString(value)) {
obj[key] = mu.getInlineFile(value);
}
else if (mu.isObject(value) && value.constructor === Object) {
mu.inlineAllFiles(value);
}
}
return obj;
}
else {
async.each(keys, (key, eCallback) => {
const value = obj[key];
if (mu.isString(value)) {
mu.getInlineFile(value, null, (err, str) => {
obj[key] = str;
eCallback();
});
}
else if (mu.isObject(value) && value.constructor === Object) {
mu.inlineAllFiles(value, eCallback);
}
else {
setImmediate(eCallback);
}
}, () => {
callback(null, obj);
});
}
}
function now() {
return Math.floor(Date.now() / 1000);
}
function nowMs() {
return Date.now();
}
function isTimeInMs(time) {
precon.positiveInteger(time, 'time');