-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathutil.ts
3344 lines (3101 loc) · 110 KB
/
util.ts
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
export type Predicate = (...item: any[]) => boolean;
export type Func<T = any> = (...args: T[]) => any;
export type MapFunc<T = any, R = any> = (
val: T,
index?: number,
arr?: T[]
) => R;
export type AnyObject = { [key: string | number]: any };
export type SortOrder = 1 | -1;
export interface IEventListener {
addEventListener: (event: string, fn: Func) => void;
}
export interface HTMLElementLike {
style: AnyObject;
dispatchEvent?: Function;
}
export interface IElement {
type: string;
props?: IElementProps;
}
export interface IElementProps {
type: string;
nodeValue?: string;
className?: string;
onClick?: Function;
children?: IElement[];
[key: string]: any;
}
export interface ArrayLike {
entries(): IterableIterator<any>;
}
export enum HTMLEscapeChars {
"&" = "&",
"<" = "<",
">" = ">",
"'" = "'",
'"' = """,
}
export enum HTMLUnEscapeChars {
"&" = "&",
"<" = "<",
">" = ">",
"'" = "'",
""" = '"',
}
const htmlEscapeReg = new RegExp(
`[${Object.keys(HTMLEscapeChars).join("")}]`,
"g"
);
const 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
*/
export const accumulate = (...nums: number[]): number[] =>
nums.reduce((acc: number[], 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
*/
export const all = <T = any>(arr: T[], fn: (t: T) => boolean = Boolean) =>
arr.every(fn);
/**
* Check if all elements in an array are equal.
*
* @param arr {T[]} <T = any>
*/
export const allEqual = <T = any>(arr: T[]) =>
arr.every((val) => val === arr[0]);
/**
* Returns `true` if both arguments are `true`, `false` otherwise.
*
* @param a {any}
* @param b {any}
*/
export const and = <T = any>(a: T, b: T) => 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
*/
export const any = <T = any>(arr: T[], fn: (t: T) => boolean = Boolean) =>
arr.some(fn);
/**
* Same as any
*
* @param arr:{T[]} <T = any>
* @param fn {function} {(t: T) => boolean } Predicate, default Boolean
*/
export const some = <T = any>(arr: T[], fn: (t: T) => boolean = 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
*/
export const aperture = <T = any>(n: number, arr: T[]) =>
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
*/
export const approximatelyEqual = (
v1: number,
v2: number,
epsilon: number = 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 ","
*/
export const arrayToCSV = (arr: (string | number)[][], 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}
*/
export const arrayToHtmlList = (arr: (string | number)[], listID: string) => {
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}
*/
export const ary =
<T = any>(fn: (...args: T[]) => any, n: number) =>
(...args: T[]) =>
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[]}
*/
export const attempt = (fn: (...args: any[]) => any, ...args: any[]) => {
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]
*/
export const attempt2 = (fn: (...args: any[]) => any, ...args: any[]) => {
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
*/
export const average = <T extends number>(...nums: number[]) =>
nums.reduce((acc, val) => acc + val, 0) / nums.length;
/**
* Returns the average of an array, after mapping each element to a value using the provided function.
*
* Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
*
* type NumCollector<T> = (item: T) => number;
* <T extends unknown>
*
* @param arr {T[]}
* @param fn {NumCollector<T> | string}
*/
type NumCollector<T> = (item: T) => number;
export const averageBy = <T = any>(arr: T[], fn: NumCollector<T> | string) => {
const mapper = typeof fn === "function" ? fn : (val: any) => 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[]}
*/
export const bifurcate = <T = any>(arr: T[], filter: boolean[]) =>
arr.reduce(
(acc, val, i) => {
acc[filter[i] ? 0 : 1].push(val);
return acc;
},
[[] as T[], [] as T[]]
);
/**
* 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>}
*/
export const bifurcateBy = <T = any>(arr: T[], filter: Predicate) =>
arr.reduce(
(acc, val) => {
acc[filter(val) ? 0 : 1].push(val);
return acc;
},
[[] as T[], [] as T[]]
);
/**
* 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)
*/
export const binary =
(fn: (...args: any[]) => any) =>
(...[v1, v2]: any[]) =>
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
*/
export const bind =
<T = any>(fn: (...args: any[]) => any, context: T, ...boundArgs: any[]) =>
(...args: any[]) =>
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[]}
*/
export const bindAll = (obj: any, ...fns: string[]) =>
fns.forEach((key: string) => {
if (typeof obj[key] === "function") {
const f = obj[key];
obj[key] = function (...args: any[]) {
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}
*/
export const binomialCoefficient = (n: number, k: number): number => {
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
*/
export const both =
(f: Function, g: Function) =>
(...args: any[]) =>
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[]}
*/
export const call =
(key: string, ...args: any[]) =>
(context: any) =>
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}
*/
export const capitalize = (str: string = "", lowerRest = false): string =>
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}
*/
export const capitalizeEveryWord = (str: string = "") =>
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
*/
export const castArray = (val: any): any[] =>
Array.isArray(val) ? val : [val];
/**
* Converts Celsius to Fahrenheit.
* Follows the conversion formula `F = 1.8C + 32`.
* @param degrees
*/
export const celsiusToFahrenheit = (degrees: number) => 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}
*/
export const chunk = (arr: any[], size: number) =>
Array.from({ length: Math.ceil(arr.length / size) }, (_: any, i: number) =>
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.
*/
export const colorize = new (class {
color = (code: number, ended = false, ...messages: any[]) =>
`\x1b[${code}m${messages.join(" ")}${ended ? "\x1b[0m" : ""}`;
black = this.color.bind(null, 30, false);
red = this.color.bind(null, 31, false);
green = this.color.bind(null, 32, false);
yellow = this.color.bind(this, 33, false);
blue = this.color.bind(this, 34, false);
magenta = this.color.bind(this, 35, false);
cyan = this.color.bind(this, 36, false);
white = this.color.bind(this, 37, false);
bgBlack = this.color.bind(this, 40, true);
bgRed = this.color.bind(this, 41, true);
bgGreen = this.color.bind(this, 42, true);
bgYellow = this.color.bind(this, 43, true);
bgBlue = this.color.bind(this, 44, true);
bgMagenta = this.color.bind(this, 45, true);
bgCyan = this.color.bind(this, 46, true);
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.
*/
export const 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[]}
*/
export const compact = (arr: any[]) => 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}
*/
export const compactWhitespace = (str: string) => 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>}
*/
export const complement =
(fn: Func) =>
(...args: any[]) =>
!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>[]}
*/
export const compose = (...fns: Func[]) =>
fns.reduce(
(f, g) =>
(...args: any[]) =>
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>[]}
*/
export const composeRight = (...fns: Func[]) =>
fns.reduce(
(f, g) =>
(...args: any[]) =>
g(...castArray(f(...args)))
);
/**
* Returns `true` if given string s1 contains s2. Compare is case insensitive.
*
*
* @param str {string}
*/
export const contains = (s1: string, s2: string = "") =>
s1.toLowerCase().indexOf(s2.toLowerCase()) !== -1;
/**
* 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}
*/
export const containsWhitespace = (str: string) => /\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
*/
export const countBy = <T = any>(arr: T[], fn: Func<T> | string) => {
const mapper = typeof fn === "function" ? fn : (val: any) => val[fn];
return arr.reduce((acc, val) => {
const value = mapper(val);
acc[value] = (acc[value] || 0) + 1;
return acc;
}, {} as any);
};
/**
* 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}
*/
export const countOccurrences = <T = any>(arr: T[], val: T) =>
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 }
*/
export const createElement = (str: string) => {
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()`.
*
*/
export const createEventHub = <T = any>() => ({
hub: Object.create(null),
emit(event: string, data?: T) {
(this.hub[event] || []).forEach((handler: Func<T | undefined>) =>
handler(data)
);
},
on(event: string, handler: Func<T>) {
if (!this.hub[event]) this.hub[event] = [];
this.hub[event].push(handler);
},
off(event: string, handler: Func<T>) {
const i = (this.hub[event] || []).findIndex((h: Func<T>) => 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
*/
export const CSVToArray = (
data: string,
delimiter = ",",
omitFirstRow = false
) =>
data
.slice(omitFirstRow ? data.indexOf("\n") + 1 : 0)
.split("\n")
.map((v) => v.split(delimiter));
/**
* Converts a comma-separated values (CSV) string to a 2D array of objects.
* The first row of the string is used as the title row.
*
* Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` and `String.prototype.split(delimiter)` to separate the first row (title row) into values.
* Use `String.prototype.split('\n')` to create a string for each row, then `Array.prototype.map()` and `String.prototype.split(delimiter)` to separate the values in each row.
* Use `Array.prototype.reduce()` to create an object for each row's values, with the keys parsed from the title row.
* Omit the second argument, `delimiter`, to use a default delimiter of `,`.
* @param data {string}
* @param delimiter {string} @default ","
*/
type StringMap<T = string> = { [key: string]: T };
export const CSVToJSON = (data: string, delimiter = ",") => {
const titles: string[] = 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),
{} as StringMap
);
});
};
/**
* 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
*/
export const curry = (fn: Func, arity = fn.length, ...args: any[]): any =>
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}
* */
export const dayOfYear = (date: Date | string): number => {
if (isString<Date>(date)) {
date = new Date(date);
}
if (!isValidDate(date)) throw new Error(`Invalid Date string`);
return Math.floor(
(date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) /
1000 /
60 /
60 /
24
);
};
/**
* Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked.
*
* Each time the debounced function is invoked, clear the current pending timeout with `clearTimeout()` and use `setTimeout()` to create a new timeout that delays invoking the function until at least `ms` milliseconds has elapsed. Use `Function.prototype.apply()` to apply the `this` context to the function and provide the necessary arguments.
* Omit the second argument, `ms`, to set the timeout at a default of 0 ms.
*
* @param fn { Function }
* @param ms {number} @default 300ms
*/
export const debounce = (fn: Function, ms = 300) => {
let timeoutId: ReturnType<typeof setTimeout>;
return function (this: any, ...args: any[]) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
};
/**
* Creates a deep clone of an object.
*
* Use recursion.
* Check if the passed object is `null` and, if so, return `null`.
* Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
* Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
*
* @param obj {any}
*/
export const deepClone = (obj: any) => {
if (obj === null) return null;
let clone = { ...obj };
Object.keys(clone).forEach(
(key) =>
(clone[key] =
typeof obj[key] === "object" ? deepClone(obj[key]) : obj[key])
);
return Array.isArray(obj) && obj.length
? (clone.length = obj.length) && Array.from(clone)
: Array.isArray(obj)
? Array.from(obj)
: clone;
};
/**
* Deep flattens an array.
*
* Use recursion.[polyfill for `Array.prototype.flat`]
* Use `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
* Recursively flatten each element that is an array.
*
* @param arr {any[]}
*/
export const deepFlatten = (arr: any[]): any[] => {
if (typeof Array.prototype.flat !== "undefined") return arr.flat(Infinity);
return [].concat(
...arr.map((v: any) => (Array.isArray(v) ? deepFlatten(v) : v))
);
};
/**
* Deep freezes an object.
*
* Use `Object.keys()` to get all the properties of the passed object, `Array.prototype.forEach()` to iterate over them.
* Call `Object.freeze(obj)` recursively on all properties, checking if each one is frozen using `Object.isFrozen()` and applying `deepFreeze()` as necessary.
* Finally, use `Object.freeze()` to freeze the given object.
*
* @param obj
*/
export const deepFreeze = <T extends object>(obj: T) => {
Object.keys(obj).forEach((prop) => {
if (
typeof obj[prop as keyof T] === "object" &&
!Object.isFrozen(obj[prop as keyof T])
) {
deepFreeze(obj[prop as keyof T]);
}
});
return Object.freeze(obj);
};
/**
* Returns the target value in a nested JSON object, based on the `keys` array.
*
* Compare the keys you want in the nested JSON object as an `Array`.
* Use `Array.prototype.reduce()` to get value from nested JSON object one by one.
* If the key exists in object, return target value, otherwise, return `null`.
*
* @param obj {any}
* @param keys {string | (string | number)[],}
* @param defaultValue {null | undefined } @default undefined
* @param delimiter {string} @default "."
*/
export const deepGet = (
obj: any,
keys: string | (string | number)[],
defaultValue: null | undefined = undefined,
delimiter = "."
) => {
if (isString(keys)) {
keys = keys.split(delimiter);
}
return keys.reduce((xs, x) => (xs && xs[x] ? xs[x] : defaultValue), obj);
};
/**
* Assigns default values for all properties in an object that are `undefined`.
*
* Use `Object.assign()` to create a new empty object and copy the original one to maintain key order, use spread operator `...` to combine the default values, finally use `obj` again to overwrite properties that originally had a value.
*
* @param obj {any}
* @param defs {any[]}
*/
export const defaults = (obj: any, ...defs: any[]) =>
Object.assign({}, obj, ...defs, obj);
/**
* Invokes the provided function after `wait` milliseconds.
*
* Use `setTimeout()` to delay execution of `fn`.
* Use the spread (`...`) operator to supply the function with an arbitrary number of arguments.
*
* @param fn {Func} any function
* @param wait {number} in ms
* @param args {any[]}, arguments for fn
*/
export const delay = (fn: Func, wait: number, ...args: any[]) =>
setTimeout(fn, wait, ...args);
/**
* Return a promise, Resolve after `wait` milliseconds.
*
* @param wait {number} in ms
* @param args{any[]}, arguments for Promise
*/
export const delayedPromise = (wait: number = 300, ...args: any[]) =>
new Promise((resolve) => {
delay(resolve, wait, ...args);
});
/**
* Returns `true` if at least one function returns `true` for a given set of arguments, `false` otherwise.
*
* Use the logical or (`||`) operator on the result of calling the two functions with the supplied `args`.
*
* @param f { Function}
* @param g { Function}
*/
export const either =
(f: Function, g: Function) =>
(...args: any[]) =>
f(...args) || g(...args);
/**
* Performs a deep comparison between two values to determine if they are equivalent.
*
* Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison).
* Check if only one value is `null` or `undefined` or if their prototypes differ.
* If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.prototype.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.
*
* @param a {<T = any = any>}
* @param b {<T = any = any>}
*/
export const equals = <T = any>(a: T, b: T): boolean => {
if (a === b) return true;
if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime();
}
if (!a || !b || (typeof a !== "object" && typeof b !== "object")) {
return a === b;
}
const objA = a as any;
const objB = b as any;
if (objA.prototype !== objA.prototype) return false;
let keys = Object.keys(objA);
if (keys.length !== Object.keys(objB).length) return false;
return keys.every((k: string) => equals(objA[k], objB[k]));
};
/**
* Performs a deep comparison between two values to determine if they are equivalent. Same as `equals`, but without type check
*
* Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison).
* Check if only one value is `null` or `undefined` or if their prototypes differ.
* If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.prototype.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.
*
* @param a {any}
* @param b {any}
*/
export const deepEquals = (a: any, b: any): boolean => {
if (a === b) return true;
if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime();
}
if (!a || !b || (typeof a !== "object" && typeof b !== "object")) {
return a === b;
}
const objA = a;
const objB = b;
if (objA.prototype !== objA.prototype) return false;
let keys = Object.keys(objA);
if (keys.length !== Object.keys(objB).length) return false;
return keys.every((k: string) => equals(objA[k], objB[k]));
};
/**
* Convert array(csv) string to doanloadable file
*
* @param csvContent
* @param name
*/
export const downloadCSV = (
csvContent: string,
name: string = "download.csv"
) => {
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", name);
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "my_data.csv".
};
/**
* Escapes a string for use in HTML.
*
* Use `String.prototype.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
*
* @param str {string}
*/
export const escapeHTML = (str: string) =>
str.replace(
htmlEscapeReg,
(tag: string) => (HTMLEscapeChars as StringMap<string>)[tag] || tag
);
/**
* Unescapes escaped HTML characters.
*
* Use `String.prototype.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
* @param str
*/
export const unescapeHTML = (str: string) =>
str.replace(
htmlUnEscapeReg,
(tag: string) => (HTMLUnEscapeChars as StringMap<string>)[tag] || tag
);
/**
* Escapes a string to use in a regular expression.
*
* Use `String.prototype.replace()` to escape special characters.
*
* @param str
*/
export const escapeRegExp = (str: string) =>
str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
/**
* Calculates the factorial of a number.
*
*Use recursion.
*If `n` is less than or equal to `1`, return `1`.
*Otherwise, return the product of `n` and the factorial of `n - 1`.
*Throws an exception if `n` is a negative number.
*
* @param n {number}
*/
export const factorial = (n: number): number =>
n <= 1 ? 1 : n * factorial(n - 1);
/**
* Returns the memoized (cached) function.
*
* Create an empty cache by instantiating a new `Map` object.
* Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. The `function` keyword must be used in order to allow the memoized function to have its `this` context changed if necessary.
* Allow access to the `cache` by setting it as a property on the returned function.
*
* @param fn {Function}
*/
export const memoize = <T = any>(fn: Func<T>) => {
const cache = new Map();
const cached = function (this: any, val: T) {
return cache.has(val)
? cache.get(val)
: cache.set(val, fn.call(this, val)) && cache.get(val);
};
cached.cache = cache;
return cached;
};