-
Notifications
You must be signed in to change notification settings - Fork 12
/
util.js
4005 lines (3994 loc) · 143 KB
/
util.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 2018-2020 the Deno authors. All rights reserved. MIT license.
// This is a specialised implementation of a System module loader.
"use strict";
// @ts-nocheck
/* eslint-disable */
let System, __instantiate;
(() => {
const r = new Map();
System = {
register(id, d, f) {
r.set(id, { d, f, exp: {} });
},
};
async function dI(mid, src) {
let id = mid.replace(/\.\w+$/i, "");
if (id.includes("./")) {
const [o, ...ia] = id.split("/").reverse(),
[, ...sa] = src.split("/").reverse(),
oa = [o];
let s = 0,
i;
while ((i = ia.shift())) {
if (i === "..") s++;
else if (i === ".") break;
else oa.push(i);
}
if (s < sa.length) oa.push(...sa.slice(s));
id = oa.reverse().join("/");
}
return r.has(id) ? gExpA(id) : import(mid);
}
function gC(id, main) {
return {
id,
import: (m) => dI(m, id),
meta: { url: id, main },
};
}
function gE(exp) {
return (id, v) => {
v = typeof id === "string" ? { [id]: v } : id;
for (const [id, value] of Object.entries(v)) {
Object.defineProperty(exp, id, {
value,
writable: true,
enumerable: true,
});
}
};
}
function rF(main) {
for (const [id, m] of r.entries()) {
const { f, exp } = m;
const { execute: e, setters: s } = f(gE(exp), gC(id, id === main));
delete m.f;
m.e = e;
m.s = s;
}
}
async function gExpA(id) {
if (!r.has(id)) return;
const m = r.get(id);
if (m.s) {
const { d, e, s } = m;
delete m.s;
delete m.e;
for (let i = 0; i < s.length; i++) s[i](await gExpA(d[i]));
const r = e();
if (r) await r;
}
return m.exp;
}
function gExp(id) {
if (!r.has(id)) return;
const m = r.get(id);
if (m.s) {
const { d, e, s } = m;
delete m.s;
delete m.e;
for (let i = 0; i < s.length; i++) s[i](gExp(d[i]));
e();
}
return m.exp;
}
__instantiate = (m, a) => {
System = __instantiate = undefined;
rF(m);
return a ? gExpA(m) : gExp(m);
};
})();
System.register("util", [], function (exports_1, context_1) {
"use strict";
var HTMLEscapeChars,
HTMLUnEscapeChars,
htmlEscapeReg,
htmlUnEscapeReg,
accumulate,
all,
allEqual,
and,
any,
some,
aperture,
approximatelyEqual,
arrayToCSV,
arrayToHtmlList,
ary,
attempt,
attempt2,
average,
averageBy,
bifurcate,
bifurcateBy,
binary,
bind,
bindAll,
binomialCoefficient,
both,
call,
capitalize,
capitalizeEveryWord,
castArray,
celsiusToFahrenheit,
chunk,
colorize,
colors,
compact,
compactWhitespace,
complement,
compose,
composeRight,
contains,
containsWhitespace,
countBy,
countOccurrences,
createElement,
createEventHub,
CSVToArray,
CSVToJSON,
curry,
dayOfYear,
debounce,
deepClone,
deepFlatten,
deepFreeze,
deepGet,
defaults,
delay,
delayedPromise,
either,
equals,
deepEquals,
downloadCSV,
escapeHTML,
unescapeHTML,
escapeRegExp,
factorial,
memoize,
fahrenheitToCelsius,
filterNonUnique,
filterNonUniqueBy,
findKey,
flatten,
forEachRight,
formatDuration,
padLeft,
formatDate,
get,
getAll,
getBaseURL,
getType,
getURLParameters,
mapToObject,
groupBy,
hasFlags,
hexToRGB,
hexToRGB2,
hide,
httpsRedirect,
includesAll,
indentString,
isFunction,
isArrayLike,
isString,
fillArray,
initializeArray,
inRange,
insertAt,
insertAtImmutable,
intersection,
intersectionBy,
intersectionWith,
is,
isAfterDate,
isBeforeDate,
isBrowser,
isEmpty,
isLeapYear,
isLowerCase,
isNil,
isNull,
isNumber,
isObject,
isPlainObject,
isPrimitive,
isSameDate,
isSorted,
isUpperCase,
isValidJSON,
JSONtoCSV,
last,
listenOnce,
lowercaseKeys,
mapKeys,
mapObject,
mapString,
map,
mask,
matches,
matchesWith,
maxBy,
maxDate,
maxN,
merge,
midpoint,
minBy,
sortBy,
SortByOrder,
sortByKey,
mostFrequent,
mostPerformant,
negate,
nest,
nodeListToArray,
toArray,
none,
not,
nthArg,
nthElement,
objectToQueryString,
offset,
omit,
omitBy,
or,
orderBy,
orderByFunc,
pad,
parseCookie,
partial,
partialRight,
partition,
partitionBy,
pick,
pickBy,
pipeAsyncFunctions,
pipeFunctions,
pluralize,
prefix,
prettyBytes,
prettyBytesT,
promisify,
radsToDegrees,
randomHexColorCode,
randomInt,
randomNumber,
reduceWhich,
removeNonASCII,
renderElement,
reverseString,
RGBToHex,
round,
runPromisesInSeries,
scrollToTop,
serializeCookie,
show,
shuffle,
size,
sleep,
splitLines,
spreadOver,
stableSort,
stripHTMLTags,
sum,
sumBy,
tail,
take,
takeRight,
takeWhile,
takeRightWhile,
throttle,
times,
timeTaken,
toCamelCase,
toDecimalMark,
toKebabCase,
humanizeUrl,
toOrdinalSuffix,
toPairs,
toSnakeCase,
toTitleCase,
transform,
triggerEvent,
truncateString,
ellipsis,
unary,
uncurry,
union,
unionBy,
unionWith,
unique,
uniqueBy,
uniqueByRight,
unzip,
unzipWith,
URLJoin,
URLJoinWithParams,
UUIDGeneratorBrowser,
validateNumber,
yesNo;
var __moduleName = context_1 && context_1.id;
/**
* Validate date
*
* @param date {Date}
*/
function isValidDate(date) {
return date instanceof Date && !isNaN(date.getTime());
}
exports_1("isValidDate", isValidDate);
return {
setters: [],
execute: function () {
(function (HTMLEscapeChars) {
HTMLEscapeChars["&"] = "&";
HTMLEscapeChars["<"] = "<";
HTMLEscapeChars[">"] = ">";
HTMLEscapeChars["'"] = "'";
HTMLEscapeChars['"'] = """;
})(HTMLEscapeChars || (HTMLEscapeChars = {}));
exports_1("HTMLEscapeChars", HTMLEscapeChars);
(function (HTMLUnEscapeChars) {
HTMLUnEscapeChars["&"] = "&";
HTMLUnEscapeChars["<"] = "<";
HTMLUnEscapeChars[">"] = ">";
HTMLUnEscapeChars["'"] = "'";
HTMLUnEscapeChars["""] = '"';
})(HTMLUnEscapeChars || (HTMLUnEscapeChars = {}));
exports_1("HTMLUnEscapeChars", HTMLUnEscapeChars);
htmlEscapeReg = new RegExp(
`[${Object.keys(HTMLEscapeChars).join("")}]`,
"g"
);
htmlUnEscapeReg = new RegExp(
`${Object.keys(HTMLUnEscapeChars).join("|")}`,
"g"
);
/**
* Returns an array of partial sums.
* Use `Array.prototype.reduce()`, `Array.prototype.slice(-1)` and the unary `+` operator to add each value to the unary array containing the previous sum.
*
* @param nums {number[]} array of numbers
*/
exports_1(
"accumulate",
(accumulate = (...nums) =>
nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)], []))
);
/**
* Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.
*
* @param arr:{T[]} <T = any>
* @param fn {function} {(t: T) => boolean } Predicate, default Boolean
*/
exports_1("all", (all = (arr, fn = Boolean) => arr.every(fn)));
/**
* Check if all elements in an array are equal.
*
* @param arr {T[]} <T = any>
*/
exports_1(
"allEqual",
(allEqual = (arr) => arr.every((val) => val === arr[0]))
);
/**
* Returns `true` if both arguments are `true`, `false` otherwise.
*
* @param a {any}
* @param b {any}
*/
exports_1("and", (and = (a, b) => Boolean(a) && Boolean(b)));
/**
* Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.
* Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.
* Omit the second argument, `fn`, to use `Boolean` as a default.
*
* @param arr:{T[]} <T = any>
* @param fn {function} {(t: T) => boolean } Predicate, default Boolean
*/
exports_1("any", (any = (arr, fn = Boolean) => arr.some(fn)));
/**
* Same as any
*
* @param arr:{T[]} <T = any>
* @param fn {function} {(t: T) => boolean } Predicate, default Boolean
*/
exports_1("some", (some = (arr, fn = Boolean) => arr.some(fn)));
/**
* Returns an array of `n`-tuples of consecutive elements.
*
* Use `Array.prototype.slice()` and `Array.prototype.map()` to create an array of appropriate length and populate it with `n`-tuples of consecutive elements from `arr`.
* If `n` is greater than the length of `arr`, return an empty array.
*
* @param n
* @param arr
*/
exports_1(
"aperture",
(aperture = (n, arr) =>
n >= arr.length
? []
: arr.slice(n - 1).map((v, i) => [...arr.slice(i, i + n - 1), v]))
);
/**
* Checks if two numbers are approximately equal to each other.
*
* Use `Math.abs()` to compare the absolute difference of the two values to `epsilon`.
* Omit the third parameter, `epsilon`, to use a default value of `0.001`.
* @param v1 {number}
* @param v2 {number}
* @param epsilon {number} default 0.001
*/
exports_1(
"approximatelyEqual",
(approximatelyEqual = (v1, v2, epsilon = 0.001) =>
Math.abs(v1 - v2) < epsilon)
);
/**
* Converts a 2D array to a comma-separated values (CSV) string.
*
* Use `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.
* Use `Array.prototype.join('\n')` to combine all rows into a CSV string, separating each row with a newline.
* Omit the second argument, `delimiter`, to use a default delimiter of `,`.
*
* @param arr {(string | number)[][]}
* @param delimiter {string} default ","
*/
exports_1(
"arrayToCSV",
(arrayToCSV = (arr, delimiter = ",") =>
arr
.map((v) =>
v
.map((x) =>
typeof x === "string" ? `"${x.replace(/"/g, '""')}"` : x
)
.join(delimiter)
)
.join("\n"))
);
/**
* Converts the given array elements into `<li>` tags and appends them to the list of the given id.
* Use `Array.prototype.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags.
*
* @param arr {(string | number)[]}
* @param listID {string}
*/
exports_1(
"arrayToHtmlList",
(arrayToHtmlList = (arr, listID) => {
let el = document.querySelector("#" + listID);
if (el) {
el.innerHTML += arr.map((item) => `<li>${item}</li>`).join("");
}
})
);
/**
* Creates a function that accepts up to `n` arguments, ignoring any additional arguments.
*
* Call the provided function, `fn`, with up to `n` arguments, using `Array.prototype.slice(0, n)` and the spread operator (`...`).
*
* @param fn {function} {(...args: T[]) => any}
* @param n {number}
*/
exports_1("ary", (ary = (fn, n) => (...args) => fn(...args.slice(0, n))));
// export const atob = (str: string) => Deno.Buffer.from(str, 'base64').toString('binary');
/**
* Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
*
* Use a `try... catch` block to return either the result of the function or an appropriate error.
*
* @param fn {function} {(...args: any[]) => any}
* @param args {any[]}
*/
exports_1(
"attempt",
(attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
})
);
/**
* Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
*
* Use a `try... catch` block to return tuple of value and Error
*
* @param fn {function} {(...args: any[]) => any}
* @param args {any[]}
*
* @returns [any, Error]
*/
exports_1(
"attempt2",
(attempt2 = (fn, ...args) => {
try {
return [fn(...args), null];
} catch (e) {
return [null, e instanceof Error ? e : new Error(e)];
}
})
);
/**
* Returns the average of two or more numbers.
*
* Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
* @param nums
*/
exports_1(
"average",
(average = (...nums) =>
nums.reduce((acc, val) => acc + val, 0) / nums.length)
);
exports_1(
"averageBy",
(averageBy = (arr, fn) => {
const mapper = typeof fn === "function" ? fn : (val) => val[fn];
return arr.reduce((acc, val) => acc + mapper(val), 0) / arr.length;
})
);
/**
* Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
*
* Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.
*
* @param arr {T[]} , <T = any>
* @param filter {boolean[]}
*/
exports_1(
"bifurcate",
(bifurcate = (arr, filter) =>
arr.reduce(
(acc, val, i) => {
acc[filter[i] ? 0 : 1].push(val);
return acc;
},
[[], []]
))
);
/**
* Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
*
* Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element.
*
* @param arr {T[]}, <T = any>
* @param filter {Predicate<T>}
*/
exports_1(
"bifurcateBy",
(bifurcateBy = (arr, filter) =>
arr.reduce(
(acc, val) => {
acc[filter(val) ? 0 : 1].push(val);
return acc;
},
[[], []]
))
);
/**
* Creates a function that accepts up to two arguments, ignoring any additional arguments.
* Call the provided function, `fn`, with the first two arguments given.
*
* @param fn {function} {(...args: any[]) => any}
* @returns {function} ([v1, v2]: any[]) => fn(v1, v2)
*/
exports_1("binary", (binary = (fn) => (...[v1, v2]) => fn(v1, v2)));
/**
* Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
*
* Return a `function` that uses `Function.prototype.apply()` to apply the given `context` to `fn`.
* Use `Array.prototype.concat()` to prepend any additional supplied parameters to the arguments.
* @param fn
* @param context
* @param boundArgs
*/
exports_1(
"bind",
(bind = (fn, context, ...boundArgs) => (...args) =>
fn.apply(context, [...boundArgs, ...args]))
);
/**
* Binds methods of an object to the object itself, overwriting the existing method
* Use `Array.prototype.forEach()` to return a `function` that uses `Function.prototype.apply()` to apply the given context (`obj`) to `fn` for each function specified.
*
* @param obj {any}
* @param fns {string[]}
*/
exports_1(
"bindAll",
(bindAll = (obj, ...fns) =>
fns.forEach((key) => {
if (typeof obj[key] === "function") {
const f = obj[key];
obj[key] = function (...args) {
return f.apply(obj, args);
};
}
}))
);
/**
* Evaluates the binomial coefficient of two integers `n` and `k`.
*
* Use `Number.isNaN()` to check if any of the two values is `NaN`.
* Check if `k` is less than `0`, greater than or equal to `n`, equal to `1` or `n - 1` and return the appropriate result.
* Check if `n - k` is less than `k` and switch their values accordingly.
* Loop from `2` through `k` and calculate the binomial coefficient.
* Use `Math.round()` to account for rounding errors in the calculation.
*
* @param n {number}
* @param k {number}
*/
exports_1(
"binomialCoefficient",
(binomialCoefficient = (n, k) => {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
})
);
/**
* Returns `true` if both functions return `true` for a given set of arguments, `false` otherwise.
* Use the logical and (`&&`) operator on the result of calling the two functions with the supplied `args`.
*
* @param f
* @param g
*/
exports_1(
"both",
(both = (f, g) => (...args) => f(...args) && g(...args))
);
// TODO: need refactor types
/**
* Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
*
* Use a closure to call a stored key with stored arguments.
*
* @param key {string}
* @param args {any[]}
*/
exports_1(
"call",
(call = (key, ...args) => (context) => context[key](...args))
);
/**
* Capitalizes the first letter of a string.
*
* Use array destructuring and `String.prototype.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
* Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
*
*
* @param str {string}
* @param lowerRest {boolean}
*/
exports_1(
"capitalize",
(capitalize = (str = "", lowerRest = false) =>
str.slice(0, 1).toUpperCase() +
(lowerRest ? str.slice(1).toLowerCase() : str.slice(1)))
);
/**
* Capitalizes the first letter of every word in a string.
* Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.
*
* @param str {string}
*/
exports_1(
"capitalizeEveryWord",
(capitalizeEveryWord = (str = "") =>
str.replace(/\b[a-z]/g, (char) => char.toUpperCase()))
);
/**
* Casts the provided value as an array if it's not one.
*
* Use `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly.
* @param val
*/
exports_1(
"castArray",
(castArray = (val) => (Array.isArray(val) ? val : [val]))
);
/**
* Converts Celsius to Fahrenheit.
* Follows the conversion formula `F = 1.8C + 32`.
* @param degrees
*/
exports_1(
"celsiusToFahrenheit",
(celsiusToFahrenheit = (degrees) => 1.8 * degrees + 32)
);
/**
* Chunks an array into smaller arrays of a specified size.
*
* Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
* Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.
* If the original array can't be split evenly, the final chunk will contain the remaining elements.
*
* @param arr {any[]}
* @param size {number}
*/
exports_1(
"chunk",
(chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
arr.slice(i * size, i * size + size)
))
);
/**
* Add special characters to text to print in color in the console (combined with `console.log()`).
*
* Use template literals and special characters to add the appropriate color code to the string output.
* For background colors, add a special character that resets the background color at the end of the string.
*/
exports_1(
"colorize",
(colorize = new (class {
constructor() {
this.color = (code, ended = false, ...messages) =>
`\x1b[${code}m${messages.join(" ")}${ended ? "\x1b[0m" : ""}`;
this.black = this.color.bind(null, 30, false);
this.red = this.color.bind(null, 31, false);
this.green = this.color.bind(null, 32, false);
this.yellow = this.color.bind(this, 33, false);
this.blue = this.color.bind(this, 34, false);
this.magenta = this.color.bind(this, 35, false);
this.cyan = this.color.bind(this, 36, false);
this.white = this.color.bind(this, 37, false);
this.bgBlack = this.color.bind(this, 40, true);
this.bgRed = this.color.bind(this, 41, true);
this.bgGreen = this.color.bind(this, 42, true);
this.bgYellow = this.color.bind(this, 43, true);
this.bgBlue = this.color.bind(this, 44, true);
this.bgMagenta = this.color.bind(this, 45, true);
this.bgCyan = this.color.bind(this, 46, true);
this.bgWhite = this.color.bind(this, 47, true);
}
})())
);
/**
* Add special characters to text to print in color in the console (combined with `console.log()`).
*
* Use template literals and special characters to add the appropriate color code to the string output.
* For background colors, add a special character that resets the background color at the end of the string.
*/
exports_1("colors", (colors = colorize));
// console.log(colorize.black("foo")); // 'foo' (red letters)
// console.log(colorize.bgBlue("foo", "bar")); // 'foo bar' (blue background)
// console.log(colorize.bgWhite(colorize.yellow("foo"), colorize.green("foo"))); // 'foo bar' (first
/**
* Removes falsy values from an array.
* Use `Array.prototype.filter()` to filter out falsy values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
*
* @param arr {any[]}
*/
exports_1("compact", (compact = (arr) => arr.filter(Boolean)));
/**
* Returns a string with whitespaces compacted.
* Use `String.prototype.replace()` with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space.
*
* @param str {string}
*/
exports_1(
"compactWhitespace",
(compactWhitespace = (str) => str.replace(/\s{2,}/g, " "))
);
/**
* Returns a function that is the logical complement of the given function, `fn`.
*
* Use the logical not (`!`) operator on the result of calling `fn` with any supplied `args`.
*
* @param fn {Func<any>}
*/
exports_1("complement", (complement = (fn) => (...args) => !fn(...args)));
/**
* Performs right-to-left function composition.
*
* Use `Array.prototype.reduce()` to perform right-to-left function composition.
* The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
*
* @param fns {...fns: Func<any>[]}
*/
exports_1(
"compose",
(compose = (...fns) =>
fns.reduce((f, g) => (...args) => f(...castArray(g(...args)))))
);
/**
* Performs left-to-right function composition.
*
* Use `Array.prototype.reduce()` to perform left-to-right function composition.
* The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. *
* @param fns {...fns: Func<any>[]}
*/
exports_1(
"composeRight",
(composeRight = (...fns) =>
fns.reduce((f, g) => (...args) => g(...castArray(f(...args)))))
);
/**
* Returns `true` if given string s1 contains s2. Compare is case insensitive.
*
*
* @param str {string}
*/
exports_1(
"contains",
(contains = (s1, s2) => s1.toLowerCase().indexOf(s2.toLowerCase()))
);
/**
* Returns `true` if the given string contains any whitespace characters, `false` otherwise.
*
* Use `RegExp.prototype.test()` with an appropriate regular expression to check if the given string contains any whitespace characters.
*
* @param str {string}
*/
exports_1(
"containsWhitespace",
(containsWhitespace = (str) => /\s/.test(str))
);
/**
* Groups the elements of an array based on the given function and returns the count of elements in each group.
*
* Use `Array.prototype.map()` to map the values of an array to a function or property name.
* Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
*
* @param arr {T[]} here <T = any>
* @param fn fn: Func<T> | string
*/
exports_1(
"countBy",
(countBy = (arr, fn) => {
const mapper = typeof fn === "function" ? fn : (val) => val[fn];
return arr.reduce((acc, val) => {
const value = mapper(val);
acc[value] = (acc[value] || 0) + 1;
return acc;
}, {});
})
);
/**
* Counts the occurrences of a value in an array.
*
* Use `Array.prototype.reduce()` to increment a counter each time you encounter the specific value inside the array.
*
* @param arr {T[]}
* @param val {T}
*/
exports_1(
"countOccurrences",
(countOccurrences = (arr, val) =>
arr.reduce((a, v) => (v === val ? a + 1 : a), 0))
);
/**
* Creates an element from a string (without appending it to the document).
* if the given string contains multiple elements, only the first one will be returned.
*
* Use `document.createElement()` to create a new element.
* Set its `innerHTML` to the string supplied as the argument.
* Use `ParentNode.firstElementChild` to return the element version of the string.
*
* @param str { string }
*/
exports_1(
"createElement",
(createElement = (str) => {
const el = document.createElement("div");
el.innerHTML = str;
return el.firstElementChild;
})
);
/**
* Creates a pub/sub ([publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.
*
* Use `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`.
* For `emit`, resolve the array of handlers based on the `event` argument and then run each one with `Array.prototype.forEach()` by passing in the data as an argument.
* For `on`, create an array for the event if it does not yet exist, then use `Array.prototype.push()` to add the handler
* to the array.
* For `off`, use `Array.prototype.findIndex()` to find the index of the handler in the event array and remove it using `Array.prototype.splice()`.
*
*/
exports_1(
"createEventHub",
(createEventHub = () => ({
hub: Object.create(null),
emit(event, data) {
(this.hub[event] || []).forEach((handler) => handler(data));
},
on(event, handler) {
if (!this.hub[event]) this.hub[event] = [];
this.hub[event].push(handler);
},
off(event, handler) {
const i = (this.hub[event] || []).findIndex((h) => h === handler);
if (i > -1) this.hub[event].splice(i, 1);
if (this.hub[event]?.length === 0) delete this.hub[event];
},
}))
);
/**
* Converts a comma-separated values (CSV) string to a 2D array.
*
* Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`.
* Use `String.prototype.split('\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.
* Omit the second argument, `delimiter`, to use a default delimiter of `,`.
* Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.
*
* @param data {string}
* @param delimiter {string} @default ","
* @param omitFirstRow {boolean} @default false
*/
exports_1(
"CSVToArray",
(CSVToArray = (data, delimiter = ",", omitFirstRow = false) =>
data
.slice(omitFirstRow ? data.indexOf("\n") + 1 : 0)
.split("\n")
.map((v) => v.split(delimiter)))
);
exports_1(
"CSVToJSON",
(CSVToJSON = (data, delimiter = ",") => {
const titles = data.slice(0, data.indexOf("\n")).split(delimiter);
return data
.slice(data.indexOf("\n") + 1)
.split("\n")
.map((v) => {
const values = v.split(delimiter);
return titles.reduce(
(obj, title, index) => ((obj[title] = values[index]), obj),
{}
);
});
})
);
/**
* Curries a function.
*
* Use recursion.
* If the number of provided arguments (`args`) is sufficient, call the passed function `fn`.
* Otherwise, return a curried function `fn` that expects the rest of the arguments.
* If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.
*
* @param fn {Func}
* @param arity {number} number of argument `fn` can have
* @param args {...any[]} var args, pass initial values
*/
exports_1(
"curry",
(curry = (fn, arity = fn.length, ...args) =>
arity <= args.length
? fn(...args)
: curry.bind(null, fn, arity, ...args))
);
/**
* dayOfYear: Gets the day of the year from a `Date` object.
*
* Use `new Date()` and `Date.prototype.getFullYear()` to get the first day of the year as a `Date` object, subtract it from the provided `date` and divide with the milliseconds in each day to get the result.
* Use `Math.floor()` to appropriately round the resulting day count to an integer.
*
* @param date {Date| string}
* */
exports_1(
"dayOfYear",
(dayOfYear = (date) => {
if (isString(date)) {