-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmap.util.ts
1845 lines (1704 loc) · 69.1 KB
/
map.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
import { Comparator, TComparator } from '@app-core/types/comparator';
import {
FFunction3,
Function2,
Function3,
PartialFunction,
TFunction0,
TFunction2,
TFunction3
} from '@app-core/types/function';
import { BinaryOperator, FBinaryOperator, TBinaryOperator } from '@app-core/types/function/operator';
import { Optional } from '@app-core/types/functional';
import { FPredicate2, Predicate2, TPredicate2 } from '@app-core/types/predicate';
import { Nullable, NullableOrUndefined, OrUndefined } from '@app-core/types';
import { ArrayUtil, AssertUtil, ObjectUtil } from '@app-core/util';
/**
* Helper functions to manage Maps.
*/
export class MapUtil {
constructor() {
throw new SyntaxError('MapUtil is an utility class');
}
/**
* Returns a new {@link Map} using the given `sourceMap`, applying {@link PartialFunction#apply} if the current element
* verifies {@link PartialFunction#isDefinedAt}, `orElseMapper` otherwise.
*
* <pre>
* applyOrElse( Result:
* [('A', 1), ('B', 2)], [('A', 2), ('B', 4)]
* PartialFunction.of(
* ([k, v]: [string, number]) => 1 == v % 2,
* ([k, v]: [string, number]) => [k, 1 + v]
* ),
* (k: string, v: number)=> [k, 2 * v]
* )
* </pre>
*
* @param sourceMap
* Source {@link Map} with the elements to filter and transform
* @param partialFunction
* {@link PartialFunction} to filter and transform elements of `sourceMap`
* @param orElseMapper
* {@link TFunction2} to transform elements of `sourceMap` do not verify {@link PartialFunction#isDefinedAt}
*
* @return new {@link Map} from applying the given {@link PartialFunction} to each element of `sourceMap`
* on which it is defined and collecting the results, `orElseMapper` otherwise
*
* @throws {IllegalArgumentError} if `partialFunction` or `orElseMapper` is `null` or `undefined` with a not empty `sourceMap`
*/
static applyOrElse<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
partialFunction: PartialFunction<[K1, V1], [K2, V2]>,
orElseMapper: TFunction2<K1, V1, [K2, V2]>): Map<K2, V2>;
/**
* Returns a new {@link Map} using the given `sourceMap`, applying `defaultMapper` if the current element verifies
* `filterPredicate`, `orElseMapper` otherwise.
*
* @apiNote
* If `filterPredicate` is `null` or `undefined` then all elements of `sourceMap` will be updated using `defaultMapper`.
*
* <pre>
* applyOrElse( Result:
* [('A', 1), ('B', 2)], [('A', 2), ('B', 4)]
* (k: string, v: number) => [k, 1 + v],
* (k: string, v: number) => [k, 2 * v],
* (k: string, v: number) => 1 == v % 2
* )
* </pre>
*
* @param sourceMap
* Source {@link Map} with the elements to filter and transform
* @param defaultMapper
* {@link TFunction2} to transform elements of `sourceMap` that verify `filterPredicate`
* @param orElseMapper
* {@link TFunction2} to transform elements of `sourceMap` do not verify `filterPredicate`
* @param filterPredicate
* {@link TPredicate2} to filter elements of `sourceMap`
*
* @return new {@link Map} from applying the given `defaultMapper` to each element of `sourceMap` that verifies `filterPredicate`
* and collecting the results, `orElseMapper` otherwise
*
* @throws {IllegalArgumentError} if `defaultMapper` or `orElseMapper` is `null` or `undefined` with a not empty `sourceMap`
*/
static applyOrElse<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
defaultMapper: TFunction2<K1, V1, [K2, V2]>,
orElseMapper: TFunction2<K1, V1, [K2, V2]>,
filterPredicate: TPredicate2<K1, V1>): Map<K2, V2>;
static applyOrElse<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
partialFunctionOrDefaultMapper: PartialFunction<[K1, V1], [K2, V2]> | TFunction2<K1, V1, [K2, V2]>,
orElseMapper: TFunction2<K1, V1, [K2, V2]>,
filterPredicate?: TPredicate2<K1, V1>): Map<K2, V2> {
const result = new Map<K2, V2>();
if (!this.isEmpty(sourceMap)) {
AssertUtil.notNullOrUndefined(
partialFunctionOrDefaultMapper,
'partialFunctionOrDefaultMapper must be not null and not undefined'
);
AssertUtil.notNullOrUndefined(
orElseMapper,
'orElseMapper must be not null and not undefined'
);
const finalPartialFunction = PartialFunction.isPartialFunction(partialFunctionOrDefaultMapper)
? <PartialFunction<[K1, V1], [K2, V2]>>partialFunctionOrDefaultMapper
: PartialFunction.of2ToTuple(
filterPredicate,
<TFunction2<K1, V1, [K2, V2]>>partialFunctionOrDefaultMapper
);
const finalOrElseMapper = Function2.of(orElseMapper);
for (let [key, value] of sourceMap!) {
const elementResult = finalPartialFunction.isDefinedAt([key, value])
? finalPartialFunction.apply([key, value])
: finalOrElseMapper.apply(key, value);
result.set(
elementResult[0],
elementResult[1]
);
}
}
return result;
}
/**
* Returns a new {@link Map} after applying to `sourceMap`:
* <p>
* - Filter its elements using {@link PartialFunction#isDefinedAt} of `partialFunction`
* - Transform its filtered elements using {@link PartialFunction#apply} of `partialFunction`
*
* <pre>
* collect( Result:
* [(1, 'Hi'), (2, 'Hello')], [(1, 2)]
* PartialFunction.of(
* ([k, v]: [number, string]) => 1 == k % 2,
* [k, v]: [number, string]) => [k, v.length]
* )
* )
* </pre>
*
* @param sourceMap
* Source {@link Map} with the elements to filter and transform
* @param partialFunction
* {@link PartialFunction} to filter and transform elements from `sourceMap`
*
* @return new {@link Map} from applying the given {@link PartialFunction} to each element of `sourceMap`
* on which it is defined and collecting the results
*
* @throws {IllegalArgumentError} if `partialFunction` is `null` or `undefined` with a not empty `sourceMap`
*/
static collect<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
partialFunction: PartialFunction<[K1, V1], [K2, V2]>): Map<K2, V2>;
/**
* Returns a new {@link Map} after applying to `sourceMap`:
* <p>
* - Filter its elements using the {@link TPredicate2} `filterPredicate`
* - Transform its filtered elements using the {@link TFunction2} `mapFunction`
*
* @apiNote
* If `filterPredicate` is `null` or `undefined` then all elements will be transformed.
*
* <pre>
* collect( Result:
* [(1, 'Hi'), (2, 'Hello')], [(1, 2)]
* (k: number, v: string) => [k, v.length],
* (k: number, v: string) => 1 == k % 2
* )
* </pre>
*
* @param sourceMap
* Source {@link Map} with the elements to filter and transform
* @param mapFunction
* {@link TFunction2} to transform filtered elements of `sourceMap`
* @param filterPredicate
* {@link TPredicate2} to filter elements from `sourceMap`
*
* @return new {@link Map} from applying the given {@link TFunction2} to each element of `sourceMap`
* on which {@link TPredicate2} returns `true` and collecting the results
*
* @throws {IllegalArgumentError} if `mapFunction` is `null` or `undefined` with a not empty `sourceMap`
*/
static collect<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
mapFunction: TFunction2<K1, V1, [K2, V2]>,
filterPredicate: TPredicate2<K1, V1>): Map<K2, V2>;
static collect<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
partialFunctionOrMapFunction: PartialFunction<[K1, V1], [K2, V2]> | TFunction2<K1, V1, [K2, V2]>,
filterPredicate?: TPredicate2<K1, V1>): Map<K2, V2> {
const result = new Map<K2, V2>();
if (!this.isEmpty(sourceMap)) {
AssertUtil.notNullOrUndefined(
partialFunctionOrMapFunction,
'partialFunctionOrMapFunction must be not null and not undefined'
);
const finalPartialFunction = PartialFunction.isPartialFunction(partialFunctionOrMapFunction)
? <PartialFunction<[K1, V1], [K2, V2]>>partialFunctionOrMapFunction
: PartialFunction.of2ToTuple(
filterPredicate,
<TFunction2<K1, V1, [K2, V2]>>partialFunctionOrMapFunction
);
for (let [key, value] of sourceMap!) {
if (finalPartialFunction.isDefinedAt([key, value])) {
const elementResult = finalPartialFunction.apply([key, value]);
result.set(
elementResult[0],
elementResult[1]
);
}
}
}
return result;
}
/**
* Returns a new {@link Map} containing the elements of provided `sourceMaps`. By default, merging `sourceMaps`
* if the key exists its value will be updated with the latest one.
*
* <pre>
* concat( Result:
* [ [(1, 'Hi'), (2, 'Dear'), (5, 'World')]
* [(1, 'Hi'), (2, 'Hello')],
* [(2, 'Dear'), (5, 'World')]
* ]
* )
* </pre>
*
* @param sourceMaps
* {@link Map}s to concat
*
* @return {@link Map} with the elements of `sourceMaps`
*/
static concat<K, V>(sourceMaps: NullableOrUndefined<Map<K, V>>[]): Map<K, V>;
/**
* Returns a new {@link Map} containing the elements of provided `sourceMaps`.
*
* <pre>
* concat( Result:
* [ [(1, 'Hi'), (2, 'Hello'), (5, 'World')]
* [(1, 'Hi'), (2, 'Hello')],
* [(2, 'Dear'), (5, 'World')]
* ],
* (oldV: string, newV: string) => oldV
* )
* </pre>
*
* @param sourceMaps
* {@link Map}s to concat
* @param mergeValueFunction
* {@link BinaryOperator} used to resolve collisions between values associated with the same key. If no one is
* provided, by default last value will be used
*
* @return {@link Map} with the elements of `sourceMaps`
*/
static concat<K, V>(sourceMaps: NullableOrUndefined<Map<K, V>>[],
mergeValueFunction: TBinaryOperator<V>): Map<K, V>;
static concat<K, V>(sourceMaps: NullableOrUndefined<Map<K, V>>[],
mergeValueFunction: FBinaryOperator<V>): Map<K, V>;
static concat<K, V>(sourceMaps: NullableOrUndefined<Map<K, V>>[],
mergeValueFunction?: TBinaryOperator<V>): Map<K, V> {
const result = new Map<K, V>();
if (!ArrayUtil.isEmpty(sourceMaps)) {
const finalMergeValueFunction: BinaryOperator<V> = ObjectUtil.isNullOrUndefined(mergeValueFunction)
? BinaryOperator.returnSecond()
: BinaryOperator.of(mergeValueFunction);
for (let i = 0; i < sourceMaps!.length; i++) {
const currentMap = sourceMaps[i];
if (!this.isEmpty(currentMap)) {
for (let [key, value] of currentMap!) {
let finalValue: V = value;
if (result.has(key)) {
finalValue = finalMergeValueFunction.apply(
result.get(key)!,
value
);
}
result.set(
key,
finalValue
);
}
}
}
}
return result;
}
/**
* Returns a new {@link Map} containing the elements of provided `sourceMap`.
*
* @param sourceMap
* {@link Map} with the elements to copy
*
* @return new {@link Map} containing all elements included in `sourceMap`
*/
static copy = <K, V>(sourceMap: NullableOrUndefined<Map<K, V>>): Map<K, V> => {
const result = new Map<K, V>();
if (!this.isEmpty(sourceMap)) {
for (let [key, value] of sourceMap!) {
result.set(key, value);
}
}
return result;
}
/**
* Counts the number of elements in `sourceMap` which satisfy the `filterPredicate`.
*
* @apiNote
* If `filterPredicate` is `null` or `undefined` then the size of `sourceMap` will be returned.
*
* <pre>
* count( Result:
* [(1, 'Hi'), (2, 'Hello')], 1
* (k: number, v: string) => 0 == k % 2
* )
* </pre>
*
* @param sourceMap
* Source {@link Map} with the elements to filter
* @param filterPredicate
* {@link TPredicate2} to filter elements from `sourceMap`
*
* @return the number of elements satisfying the {@link TPredicate2} `filterPredicate`
*/
static count = <K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
filterPredicate: NullableOrUndefined<TPredicate2<K, V>>): number => {
if (this.isEmpty(sourceMap)) {
return 0;
}
if (ObjectUtil.isNullOrUndefined(filterPredicate)) {
return sourceMap!.size;
}
const finalFilterPredicate = Predicate2.of(filterPredicate);
let result = 0;
for (let [key, value] of sourceMap!) {
if (finalFilterPredicate.apply(key, value)) {
result++;
}
}
return result;
}
/**
* Returns a {@link Map} removing the longest prefix of elements included in `sourceMap` that satisfy the
* {@link TPredicate2} `filterPredicate`.
*
* @apiNote
* If `filterPredicate` is `null` or `undefined` then all elements of `sourceMap` will be returned.
*
* <pre>
* dropWhile( Result:
* [(2, 'Hi'), (4, 'Hello'), (3, 'World')], [(3, 'World')]
* (k: number, v: string) => 0 == k % 2
* )
* </pre>
*
* @param sourceMap
* {@link Map} to filter
* @param filterPredicate
* {@link TPredicate2} used to find given elements to filter
*
* @return the longest suffix of provided `sourceMap` whose elements all satisfy `filterPredicate`
*/
static dropWhile = <K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
filterPredicate: NullableOrUndefined<TPredicate2<K, V>>): Map<K, V> => {
if (this.isEmpty(sourceMap) ||
ObjectUtil.isNullOrUndefined(filterPredicate)) {
return this.copy(sourceMap);
}
const finalFilterPredicate = Predicate2.of(filterPredicate!);
const result = new Map<K, V>();
let wasFoundFirstElementDoesMatchPredicate = false;
if (!this.isEmpty(sourceMap)) {
for (let [key, value] of sourceMap!) {
if (!finalFilterPredicate.apply(key, value) &&
!wasFoundFirstElementDoesMatchPredicate) {
wasFoundFirstElementDoesMatchPredicate = true;
}
if (wasFoundFirstElementDoesMatchPredicate) {
result.set(
key,
value
);
}
}
}
return result;
}
/**
* Returns a new {@link Map} using `sourceMap` as source, adding from the result the elements that verify the
* given {@link TPredicate2} `filterPredicate`.
*
* @apiNote
* If `filterPredicate` is `null` or `undefined` then all elements of `sourceMap` will be returned.
*
* <pre>
* filter( Result:
* [(1, 'Hi'), (2, 'Hello'), (3, 'World')], [(3, 'World')]
* (k: number, v: string) => 1 == k % 2 && 2 < v.length()
* )
* </pre>
*
* @param sourceMap
* {@link Map} to filter
* @param filterPredicate
* {@link TPredicate2} used to find given elements to filter
*
* @return empty {@link Map} if `sourceMap` has no elements or no one verifies provided `filterPredicate`,
* otherwise a new {@link Map} with the elements of `sourceMap` which verify `filterPredicate`
*/
static filter = <K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
filterPredicate: NullableOrUndefined<TPredicate2<K, V>>): Map<K, V> => {
if (this.isEmpty(sourceMap) ||
ObjectUtil.isNullOrUndefined(filterPredicate)) {
return this.copy(sourceMap);
}
const finalFilterPredicate = Predicate2.of(filterPredicate);
const result = new Map<K, V>();
for (let [key, value] of sourceMap!) {
if (finalFilterPredicate.apply(key, value)) {
result.set(key, value);
}
}
return result;
}
/**
* Returns a new {@link Map} using `sourceMap` as source, removing from the result the elements that verify the
* given {@link TPredicate2} `filterPredicate`.
*
* @apiNote
* If `filterPredicate` is `null` or `undefined` then all elements of `sourceMap` will be returned.
*
* <pre>
* filterNot( Result:
* [(1, 'Hi'), (2, 'Hello'), (3, 'World')], [(1, 'Hi'), (2, 'Hello')]
* (k: number, v: string) => 1 == k % 2 && 2 > v.length()
* )
* </pre>
*
* @param sourceMap
* {@link Map} to filter
* @param filterPredicate
* {@link TPredicate2} used to find given elements to filter
*
* @return empty {@link Map} if `sourceMap` has no elements,
* otherwise a new {@link Map} with the elements of `sourceMap` which do not verify `filterPredicate`
*/
static filterNot = <K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
filterPredicate: NullableOrUndefined<TPredicate2<K, V>>): Map<K, V> => {
const finalFilterPredicate = ObjectUtil.isNullOrUndefined(filterPredicate)
? null
: Predicate2.of(filterPredicate).not();
return this.filter(
sourceMap,
finalFilterPredicate
);
}
/**
* Returns from the given `sourceMap` the first element that verifies the provided `filterPredicate`.
*
* <pre>
* find( Result:
* [(1, 'Hi'), (2, 'Hello'), (3, 'World')], (3, 'World')
* (k: number, v: string) => 1 == k % 2 && 2 > v.length()
* )
* </pre>
*
* @param sourceMap
* {@link Map} to search
* @param filterPredicate
* {@link TPredicate2} used to find given elements to filter
*
* @return `undefined` if `sourceMap` has no elements, `filterPredicate` is `null` or `undefined`
* or no one verifies provided `filterPredicate`.
* Otherwise, a tuple with the first element that verifies `filterPredicate`.
*/
static find = <K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
filterPredicate: TPredicate2<K, V>): OrUndefined<[K, V]> => {
if (!this.isEmpty(sourceMap) &&
ObjectUtil.nonNullOrUndefined(filterPredicate)) {
const finalFilterPredicate = Predicate2.of(filterPredicate);
for (let [key, value] of sourceMap!) {
if (finalFilterPredicate.apply(key, value)) {
return [key, value];
}
}
}
return undefined;
}
/**
* Returns an {@link Optional} containing the first element of the given `sourceMap` hat verifies the provided
* `filterPredicate`, {@link Optional#empty} otherwise.
*
* <pre>
* findOptional( Result:
* [(1, 'Hi'), (2, 'Hello'), (3, 'World')], Optional(3, 'World')
* (k: number, v: string) => 1 == k % 2 && 2 > v.length()
* )
* </pre>
*
* @param sourceMap
* {@link Map} to search
* @param filterPredicate
* {@link TPredicate2} used to find given elements to filter
*
* @return {@link Optional} containing the first element that satisfies `filterPredicate`,
* {@link Optional#empty} otherwise.
*/
static findOptional = <K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
filterPredicate: TPredicate2<K, V>): Optional<[K, V]> =>
Optional.ofNullable(
this.find(
sourceMap,
filterPredicate
)
);
/**
* Using the given value `initialValue` as initial one, applies the provided {@link TFunction3} to all
* elements of `sourceMap`, going left to right.
*
* @apiNote
* If `sourceMap` or `accumulator` are `null` or `undefined` then `initialValue` is returned.
*
* <pre>
* foldLeft( Result:
* [(1, 'Hi'), (2, 'Hello')], 10
* 0,
* (prev: number, k: number, v: string) => prev + k + v.length()
* )
* </pre>
*
* @param sourceMap
* {@link Map} with elements to combine
* @param initialValue
* The initial value to start with
* @param accumulator
* A {@link TFunction3} which combines elements
*
* @return result of inserting `accumulator` between consecutive elements of `sourceMap`, going
* left to right with the start value `initialValue` on the left.
*/
static foldLeft<K, V, R>(sourceMap: NullableOrUndefined<Map<K, V>>,
initialValue: R,
accumulator: NullableOrUndefined<TFunction3<R, K, V, R>>): R;
static foldLeft<K, V, R>(sourceMap: NullableOrUndefined<Map<K, V>>,
initialValue: R,
accumulator: NullableOrUndefined<FFunction3<R, K, V, R>>): R;
/**
* Using the given value `initialValue` as initial one, applies the provided {@link TFunction3} to all
* elements of `sourceMap`, going left to right.
*
* @apiNote
* If `sourceMap` or `accumulator` are `null` or `undefined` then `initialValue` is returned. If `filterPredicate`
* is `null` or `undefined` then all elements will be used to calculate the final value.
*
* <pre>
* foldLeft( Result:
* [(1, 'Hi'), (2, 'Hello'), (3, 'World')], 3
* 0,
* (prev: number, k: number, v: string) => prev + k + v.length(),
* (k: number, v: string) => 1 == k % 2 && 2 < v.length()
* )
* </pre>
*
* @param sourceMap
* {@link Map} with elements to combine
* @param initialValue
* The initial value to start with
* @param accumulator
* A {@link TFunction3} which combines elements
* @param filterPredicate
* {@link TPredicate2} used to find given elements to filter
*
* @return result of inserting `accumulator` between consecutive elements `sourceMap`, going
* left to right with the start value `initialValue` on the left.
*/
static foldLeft<K, V, R>(sourceMap: NullableOrUndefined<Map<K, V>>,
initialValue: R,
accumulator: NullableOrUndefined<TFunction3<R, K, V, R>>,
filterPredicate: TPredicate2<K, V>): R;
static foldLeft<K, V, R>(sourceMap: NullableOrUndefined<Map<K, V>>,
initialValue: R,
accumulator: NullableOrUndefined<FFunction3<R, K, V, R>>,
filterPredicate: TPredicate2<K, V>): R;
static foldLeft<K, V, R>(sourceMap: NullableOrUndefined<Map<K, V>>,
initialValue: R,
accumulator: NullableOrUndefined<TFunction3<R, K, V, R>>,
filterPredicate?: TPredicate2<K, V>): R {
if (this.isEmpty(sourceMap) ||
ObjectUtil.isNullOrUndefined(accumulator)) {
return initialValue
}
const finalAccumulator = Function3.of(accumulator);
const finalFilterPredicate = ObjectUtil.isNullOrUndefined(filterPredicate)
? Predicate2.alwaysTrue<K, V>()
: Predicate2.of(filterPredicate);
let result: R = initialValue;
for (let [key, value] of sourceMap!) {
if (finalFilterPredicate.apply(key, value)) {
result = finalAccumulator.apply(
result,
key,
value
);
}
}
return result;
}
/**
* Verifies if the given `mapToVerify` contains at least one element.
*
* @param mapToVerify
* {@link Map} to verify
*
* @return `true` if `mapToVerify` is `undefined`, `null` or empty.
* `false` otherwise.
*/
static isEmpty = (mapToVerify?: Nullable<Map<any, any>>): boolean =>
ObjectUtil.isNullOrUndefined(mapToVerify) ||
0 == mapToVerify!.size;
/**
* Returns the value associated with the given `key` if `sourceMap` contains it, `defaultValue` otherwise.
*
* <pre>
* getOrElse( Result:
* [(1, 'Hi'), (2, 'Hello')], 'Hi'
* 1,
* 'World'
* )
* </pre>
*
* @param sourceMap
* {@link Map} to search `key`
* @param key
* Key to search in `sourceMap`
* @param defaultValue
* Default value to return in case no binding for `key` is found in `sourceMap`
*
* @return value associated with the given `key` if `sourceMap` contains it,
* `defaultValue` otherwise.
*/
static getOrElse<K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
key: K,
defaultValue: V): V;
/**
* Returns the value associated with the given `key` if `sourceMap` contains it, the result after invoking
* `defaultValue` otherwise.
*
* <pre>
* getOrElse( Result:
* [(1, 'Hi'), (2, 'Hello')] 'World'
* 5,
* () => 'World'
* )
* </pre>
*
* @param sourceMap
* {@link Map} to search `key`
* @param key
* Key to search in `sourceMap`
* @param defaultValue
* {@link TFunction0} that yields a default value in case no binding for `key` is found in `sourceMap`
*
* @return value associated with the given `key` if `sourceMap` contains it,
* `defaultValue` results otherwise.
*/
static getOrElse<K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
key: K,
defaultValue: TFunction0<V>): V;
static getOrElse<K, V>(sourceMap: NullableOrUndefined<Map<K, V>>,
key: K,
defaultValue: TFunction0<V> | V): V {
const finalSourceMap = ObjectUtil.getOrElse(
sourceMap,
new Map<K, V>()
);
// @ts-ignore
return Optional.ofNullable(key)
.map(k => finalSourceMap.get(k))
.getOrElse(defaultValue);
}
/**
* Partitions `sourceMap` into a {@link Map} of maps according to given `discriminator` {@link TFunction2}.
*
* @apiNote
* If `filterPredicate` is `null` or `undefined` then all elements will be used.
*
* <pre>
* groupBy( Result:
* [(1, 'Hi'), (2, 'Hello'), (7, 'World'), (11, 'Ok')], [(0, [(2, 'Hello')])
* (k: number, v: string) => k % 2, (1, [(1, 'Hi'), (7, 'World')]]
* (k: number, v: string) => 10 > k
* )
* </pre>
*
* @param sourceMap
* {@link Map} to filter and group
* @param discriminator
* {@link TFunction2} used to split the elements of `sourceMap`
* @param filterPredicate
* {@link TPredicate2} to filter elements of `sourceMap`
*
* @return new {@link Map} from applying the given {@link TFunction2} to each element of `sourceMap` to generate
* the keys of the returned one
*
* @throws {IllegalArgumentError} if `discriminator` is `null` or `undefined` with a not empty `sourceMap`
*/
static groupBy = <K, V, R>(sourceMap: NullableOrUndefined<Map<K, V>>,
discriminator: TFunction2<K, V, R>,
filterPredicate?: TPredicate2<K, V>): Map<R, Map<K, V>> => {
const result = new Map<R, Map<K, V>>();
if (!this.isEmpty(sourceMap)) {
AssertUtil.notNullOrUndefined(
discriminator,
'discriminator must be not null and not undefined'
);
const finalDiscriminator = Function2.of(discriminator);
const finalFilterPredicate = ObjectUtil.isNullOrUndefined(filterPredicate)
? Predicate2.alwaysTrue<K, V>()
: Predicate2.of(filterPredicate);
for (let [key, value] of sourceMap!) {
if (finalFilterPredicate.apply(key, value)) {
const discriminatorResult = finalDiscriminator.apply(
key,
value
);
MapUtil.setIfAbsent(
result,
discriminatorResult,
new Map<K, V>()
);
result.get(discriminatorResult)!
.set(
key,
value
);
}
}
}
return result;
}
/**
* Partitions `sourceMap` into a {@link Map} of maps according to given `discriminator` {@link TFunction2}.
*
* @apiNote
* This method is to {@link MapUtil#groupBy} but `discriminator` returns an array of related key values.
*
* <pre>
* groupByMultiKey( Result:
* [(1, 'Hi'), (2, 'Hello'), (7, 'World'), (11, 'Ok')], [('evenKey', [(2, 'Hello')])
* (k: number, v: string) => { ('oddKey', [(1, 'Hi'), (7, 'World')]]
* const keys: string[] = []; ('smaller5Key', [(1, 'Hi'), (2, 'Hello')])
* if (0 == k % 2) { ('greaterEqual5Key', [(7, 'World')])]
* keys.push('evenKey');
* else {
* keys.push('oddKey');
* }
* if (5 > k) {
* keys.push('smaller5Key');
* } else {
* keys.push('greaterEqual5Key');
* }
* return keys;
* },
* (k: number, v: string) => 10 > k
* )
* </pre>
*
* @param sourceMap
* {@link Map} to filter and group
* @param discriminator
* {@link TFunction2} used to split the elements of `sourceMap`
* @param filterPredicate
* {@link TPredicate2} to filter elements of `sourceMap`
*
* @return new {@link Map} from applying the given {@link TFunction2} to each element of `sourceMap` to generate
* the keys of the returned one
*
* @throws {IllegalArgumentError} if `discriminator` is `null` or `undefined` with a not empty `sourceMap`
*/
static groupByMultiKey = <K, V, R>(sourceMap: NullableOrUndefined<Map<K, V>>,
discriminator: TFunction2<K, V, R[]>,
filterPredicate?: TPredicate2<K, V>): Map<R, Map<K, V>> => {
const result = new Map<R, Map<K, V>>();
if (!this.isEmpty(sourceMap)) {
AssertUtil.notNullOrUndefined(
discriminator,
'discriminator must be not null and not undefined'
);
const finalDiscriminator = Function2.of(discriminator);
const finalFilterPredicate = ObjectUtil.isNullOrUndefined(filterPredicate)
? Predicate2.alwaysTrue<K, V>()
: Predicate2.of(filterPredicate);
for (let [key, value] of sourceMap!) {
if (finalFilterPredicate.apply(key, value)) {
const discriminatorResult = ObjectUtil.getOrElse(
finalDiscriminator.apply(
key,
value
),
[]
);
for (let i = 0; i < discriminatorResult.length; i++) {
MapUtil.setIfAbsent(
result,
discriminatorResult[i],
new Map<K, V>()
);
result.get(discriminatorResult[i])!
.set(
key,
value
);
}
}
}
}
return result;
}
/**
* Partitions given `sourceMap` into a {@link Map}, applying {@link PartialFunction#apply} and adding values with
* the same `key` in an array of values.
*
* <pre>
* groupMap( Result:
* [(1, 'Hi'), (2, 'Hello'), (7, 'World'), (8, 'Ok')], [(1, [2, 5])
* PartialFunction.of( (2, [2])]
* ([k, v]: [number, string]) => 1 == k % 2 || 6 < k,
* ([k, v]: [number, string]) => [k % 3, v.length]
* )
* )
* </pre>
*
* @param sourceMap
* {@link Map} with the elements to filter, transform and group
* @param partialFunction
* {@link PartialFunction} to filter and transform elements of `sourceMap`
*
* @return new {@link Map} from applying the given {@link PartialFunction} to each element of `sourceMap`
* on which it is defined and collecting the results
*
* @throws {IllegalArgumentError} if `partialFunction` is `null` or `undefined` with a not empty `sourceMap`
*/
static groupMap<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
partialFunction: PartialFunction<[K1, V1], [K2, V2]>): Map<K2, V2[]>;
/**
* Partitions given `sourceMap` into a {@link Map}, applying `discriminatorKey` and `valueMapper` if the current
* element verifies `filterPredicate`. All values with the same `key` will be added in an array.
*
* @apiNote
* If `filterPredicate` is `null` or `undefined` then all elements will be used.
*
* <pre>
* groupMap( Result:
* [(1, 'Hi'), (2, 'Hello'), (7, 'World'), (8, 'Ok')], [(1, [2, 5])
* (k: number, v: string) => k % 3, (2, [2])]
* (k: number, v: string) => v.length,
* (k: number, v: string) => 1 == k % 2 || 6 < k
* )
* </pre>
*
* @param sourceMap
* {@link Map} with the elements to filter and transform
* @param discriminatorKey
* The discriminator {@link TFunction2} to get the key values of returned {@link Map}
* @param valueMapper
* {@link TFunction2} to transform elements of `sourceMap`
* @param filterPredicate
* {@link TPredicate2} to filter elements of `sourceMap`
*
* @return new {@link Map} from applying the given `discriminatorKey` and `valueMapper` to each element of `sourceMap`
* that verifies `filterPredicate`
*
* @throws {IllegalArgumentError} if `discriminatorKey` or `valueMapper` is `null` or `undefined` with a not empty `sourceMap`
*/
static groupMap<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
discriminatorKey: TFunction2<K1, V1, K2>,
valueMapper: TFunction2<K1, V1, V2>,
filterPredicate?: TPredicate2<K1, V1>): Map<K2, V2[]>;
static groupMap<K1, K2, V1, V2>(sourceMap: NullableOrUndefined<Map<K1, V1>>,
partialFunctionOrDiscriminatorKey: PartialFunction<[K1, V1], [K2, V2]> | TFunction2<K1, V1, K2>,
valueMapper?: TFunction2<K1, V1, V2>,
filterPredicate?: TPredicate2<K1, V1>): Map<K2, V2[]> {
const result: Map<K2, V2[]> = new Map<K2, V2[]>();
if (!this.isEmpty(sourceMap)) {
AssertUtil.notNullOrUndefined(
partialFunctionOrDiscriminatorKey,
'partialFunctionOrDiscriminatorKey must be not null and not undefined'
);
const finalPartialFunction = PartialFunction.isPartialFunction(partialFunctionOrDiscriminatorKey)
? <PartialFunction<[K1, V1], [K2, V2]>>partialFunctionOrDiscriminatorKey
: PartialFunction.of2KeyValueMapper(
filterPredicate,
<TFunction2<K1, V1, K2>>partialFunctionOrDiscriminatorKey,
<TFunction2<K1, V1, V2>>valueMapper
);
for (let [key, value] of sourceMap!) {
if (finalPartialFunction.isDefinedAt([key, value])) {
const pairKeyValue: [K2, V2] = <[K2, V2]>finalPartialFunction.apply([key, value]);
MapUtil.setIfAbsent(
result,
pairKeyValue[0],
[]
);
result.get(pairKeyValue[0])!
.push(pairKeyValue[1]);
}
}
}
return result;
}
/**
* Partitions given `sourceMap` into a {@link Map} of arrays as values, according to `partialFunction`.
* If the current element verifies {@link PartialFunction#isDefinedAt}, all the values that have the same `key`
* after applying {@link PartialFunction#apply} are then reduced into a single value with `reduceValues`.
*
* <pre>
* groupMapReduce( Intermediate Map: Result:
* [(1, 'Hi'), (2, 'Hola'), (4, ''), (5, 'World'), (6, '!'), (11, 'ABC')], [(0, [2]) [(0, 2),
* (n1: number, n2: number) => n1 + n2, (1, [3, 1]) (1, 4)
* PartialFunction.of( (2, [5, 6])] (2, 11)]
* ([k, v]: [number, string]) => 10 > k,
* ([k, v]: [number, string]) => [k % 3, v.length + 1]
* )
* )
* </pre>
*
* @param sourceMap
* {@link Map} with the elements to filter, transform, group and reduce
* @param reduceValues
* {@link BinaryOperator} used to reduce the values related with same key
* @param partialFunction