-
Notifications
You must be signed in to change notification settings - Fork 1
/
slice.go
1738 lines (1488 loc) · 45 KB
/
slice.go
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
package gg
import (
"sort"
)
/*
Syntactic shortcut for creating a slice out of the given values. Simply returns
the slice of arguments as-is. Sometimes allows shorter code. Note that when
calling this function with an existing slice, you get the EXACT same slice
back, with no allocation. Also see `SliceOf` which returns `Slice[A]` rather
than `[]A`.
*/
func ToSlice[A any](val ...A) []A { return val }
/*
Syntactic shortcut for making `Slice[A]` out of the given values. Can also be
used to perform a free type conversion from an existing slice, with no
allocation. Also see `ToSlice` which returns `[]A` rather than `Slice[A]`.
*/
func SliceOf[A any](val ...A) Slice[A] { return Slice[A](val) }
/*
Shortcut for converting an arbitrary number of slices to `Slice[Elem]`. When
called with exactly one argument, this performs a free type conversion without
an allocation. When called with 2 or more arguments, this concatenates the
inputs, allocating a new slice.
*/
func SliceFrom[Src ~[]Elem, Elem any](src ...Src) Slice[Elem] {
switch len(src) {
case 0:
return nil
case 1:
return Slice[Elem](src[0])
default:
return Slice[Elem](Concat(src...))
}
}
/*
Typedef of an arbitrary slice with various methods that duplicate global slice
functions such as `Get` or `Filter`. Useful as a shortcut for creating bound
methods that can be passed to higher-order functions. Example:
values := []string{`one`, `two`, `three`}
indexes := []int{0, 2}
result := Map(indexes, SliceOf(values...).Get)
fmt.Println(grepr.String(result))
// []string{`one`, `three`}
*/
type Slice[A any] []A
// Free cast from a typedef to a plain slice.
func (self Slice[A]) Plain() []A { return self }
// True if len <= 0. Inverse of `.IsNotEmpty`.
func IsEmpty[Slice ~[]Elem, Elem any](val Slice) bool { return len(val) <= 0 }
// Same as global `IsEmpty`.
func (self Slice[_]) IsEmpty() bool { return IsEmpty(self) }
// True if len > 0. Inverse of `.IsEmpty`.
func IsNotEmpty[Slice ~[]Elem, Elem any](val Slice) bool { return len(val) > 0 }
// Same as global `IsNotEmpty`.
func (self Slice[_]) IsNotEmpty() bool { return IsNotEmpty(self) }
// Same as `len(val)` but can be passed to higher-order functions.
func Len[Slice ~[]Elem, Elem any](val Slice) int { return len(val) }
// Same as global `Len`.
func (self Slice[_]) Len() int { return len(self) }
// Same as `len(PtrGet(val))` but can be passed to higher-order functions.
func PtrLen[Slice ~[]Elem, Elem any](val *Slice) int { return len(PtrGet(val)) }
// Same as global `PtrLen`.
func (self *Slice[_]) PtrLen() int { return PtrLen(self) }
// Same as `cap(val)` but can be passed to higher-order functions.
func Cap[Slice ~[]Elem, Elem any](val Slice) int { return cap(val) }
// Same as global `Cap`.
func (self Slice[_]) Cap() int { return cap(self) }
// Amount of unused capacity in the given slice.
func CapUnused[Slice ~[]Elem, Elem any](src Slice) int { return cap(src) - len(src) }
// Same as global `CapUnused`.
func (self Slice[_]) CapUnused() int { return CapUnused(self) }
/*
Amount of missing capacity that needs to be allocated to append the given amount
of additional elements.
*/
func CapMissing[Slice ~[]Elem, Elem any](src Slice, size int) int {
return MaxPrim2(0, size-CapUnused(src))
}
// Same as global `CapMissing`.
func (self Slice[_]) CapMissing(size int) int { return CapMissing(self, size) }
// Counts the total length of the given slices.
func Lens[Slice ~[]Elem, Elem any](val ...Slice) int { return Sum(val, Len[Slice]) }
// Grows the length of the given slice by appending N zero values.
func GrowLen[Slice ~[]Elem, Elem any](src Slice, size int) Slice {
return append(src, make(Slice, size)...)
}
// Same as global `GrowLen`.
func (self Slice[A]) GrowLen(size int) Slice[A] { return GrowLen(self, size) }
/*
Missing feature of the language / standard library. Ensures at least this much
unused capacity (not total capacity). If there is already enough capacity,
returns the slice as-is. Otherwise allocates a new slice, doubling the capacity
as many times as needed until it accommodates enough elements. Use this when
further growth is expected. When further growth is not expected, use
`GrowCapExact` instead. Similar to `(*bytes.Buffer).Grow` but works for all
slice types and avoids any wrapping, unwrapping, or spurious escapes to the
heap.
*/
func GrowCap[Slice ~[]Elem, Elem any](src Slice, size int) Slice {
missing := CapMissing(src, size)
if !(missing > 0) {
return src
}
prev := MaxPrim2(0, cap(src))
next := Or(prev, 1)
for next < prev+size {
next *= 2
}
out := make(Slice, len(src), next)
copy(out, src)
return out
}
// Same as global `GrowCap`.
func (self Slice[A]) GrowCap(size int) Slice[A] { return GrowCap(self, size) }
/*
Missing feature of the language / standard library. Ensures at least this much
unused capacity (not total capacity). If there is already enough capacity,
returns the slice as-is. Otherwise allocates a new slice with EXACTLY enough
additional capacity. Use this when further growth is not expected. When further
growth is expected, use `GrowCap` instead.
*/
func GrowCapExact[Slice ~[]Elem, Elem any](src Slice, size int) Slice {
missing := CapMissing(src, size)
if !(missing > 0) {
return src
}
out := make(Slice, len(src), cap(src)+missing)
copy(out, src)
return out
}
// Same as global `GrowCapExact`.
func (self Slice[A]) GrowCapExact(size int) Slice[A] { return GrowCapExact(self, size) }
/*
Returns a modified slice where length is reduced to the given size. Negative
size is equivalent to zero. If the current length is already shorter, it's
unaffected.
*/
func TruncLen[Slice ~[]Elem, Elem any](src Slice, size int) Slice {
if size < len(src) {
if size < 0 {
return src[:0]
}
return src[:size]
}
return src
}
// Same as global `TruncLen`.
func (self Slice[A]) TruncLen(size int) Slice[A] { return TruncLen(self, size) }
/*
Zeroes each element of the given slice. Note that Go 1.21 and higher have an
equivalent built-in function `clear`.
*/
func SliceZero[A any](val []A) {
var zero A
for ind := range val {
val[ind] = zero
}
}
// Same as global `SliceZero`.
func (self Slice[_]) Zero() { SliceZero(self) }
/*
Collapses the slice's length, preserving the capacity. Does not modify any
elements. If the pointer is nil, does nothing.
*/
func Trunc[Slice ~[]Elem, Elem any](ptr *Slice) {
if ptr == nil {
return
}
tar := *ptr
if tar != nil {
*ptr = tar[:0]
}
}
// Same as global `Trunc`.
func (self *Slice[_]) Trunc() { Trunc(self) }
/*
If the index is within bounds, returns the value at that index and true.
Otherwise returns zero value and false.
*/
func Got[A any](src []A, ind int) (A, bool) {
if ind >= 0 && ind < len(src) {
return src[ind], true
}
return Zero[A](), false
}
// Same as global `Got`.
func (self Slice[A]) Got(ind int) (A, bool) { return Got(self, ind) }
/*
If the index is within bounds, returns the value at that index.
Otherwise returns zero value.
*/
func Get[A any](src []A, ind int) A {
if ind >= 0 && ind < len(src) {
return src[ind]
}
return Zero[A]()
}
// Same as global `Get`.
func (self Slice[A]) Get(ind int) A { return Get(self, ind) }
/*
Same as `slice[index]`, expressed as a function. Panics if the index is out of
bounds. Sometimes useful with higher-order functions. Also see `Get` which
returns zero value instead of panicking when the index is out of bounds.
*/
func GetStrict[A any](src []A, ind int) A { return src[ind] }
// Same as global `GetStrict`.
func (self Slice[A]) GetStrict(ind int) A { return self[ind] }
/*
If the index is within bounds, returns a pointer to the value at that index.
Otherwise returns nil.
*/
func GetPtr[A any](src []A, ind int) *A {
if ind >= 0 && ind < len(src) {
return &src[ind]
}
return nil
}
// Same as global `GetPtr`.
func (self Slice[A]) GetPtr(ind int) *A { return GetPtr(self, ind) }
/*
Sets a value at an index, same as by using the built-in square bracket syntax.
Useful as a shortcut for inline bound functions.
*/
func (self Slice[A]) Set(ind int, val A) { self[ind] = val }
/*
Returns a shallow copy of the given slice. The capacity of the resulting slice
is equal to its length.
*/
func Clone[Slice ~[]Elem, Elem any](src Slice) Slice {
if src == nil {
return nil
}
out := make(Slice, len(src))
copy(out, src)
return out
}
// Same as global `Clone`.
func (self Slice[A]) Clone() Slice[A] { return Clone(self) }
/*
Same as `append`, but makes a copy instead of mutating the original.
Useful when reusing one "base" slice for in multiple append calls.
*/
func CloneAppend[Slice ~[]Elem, Elem any](src Slice, val ...Elem) Slice {
if src == nil && val == nil {
return nil
}
out := make(Slice, 0, len(src)+len(val))
out = append(out, src...)
out = append(out, val...)
return out
}
// Same as global `CloneAppend`.
func (self Slice[A]) CloneAppend(val ...A) Slice[A] {
return CloneAppend(self, val...)
}
/*
Appends the given elements to the given slice. Similar to built-in `append` but
syntactically shorter.
*/
func Append[Slice ~[]Elem, Elem any](ptr *Slice, val ...Elem) {
if ptr != nil {
*ptr = append(*ptr, val...)
}
}
// Same as global `Append`.
func (self *Slice[A]) Append(val ...A) { Append(self, val...) }
/*
If the target pointer is nil, does nothing and returns -1. Otherwise appends the
given element to the given slice (like `Append`) and returns the last index
of the resulting slice. Also see `AppendPtr`.
*/
func AppendIndex[Slice ~[]Elem, Elem any](ptr *Slice, val Elem) int {
if ptr == nil {
return -1
}
tar := *ptr
tar = append(tar, val)
*ptr = tar
return LastIndex(tar)
}
// Same as global `AppendIndex`.
func (self *Slice[A]) AppendIndex(val A) int { return AppendIndex(self, val) }
/*
Appends the given element to the given slice, returning the pointer to the newly
appended position in the slice. If the target pointer is nil, does nothing and
returns nil. Also see `AppendIndex`.
*/
func AppendPtr[Slice ~[]Elem, Elem any](ptr *Slice, val Elem) *Elem {
if ptr == nil {
return nil
}
tar := append(*ptr, val)
*ptr = tar
return LastPtr(tar)
}
// Same as global `AppendPtr`.
func (self *Slice[A]) AppendPtr(val A) *A { return AppendPtr(self, val) }
/*
Appends a zero element to the given slice, returning the pointer to the newly
appended position in the slice. If the target pointer is nil, does nothing and
returns nil.
*/
func AppendPtrZero[Slice ~[]Elem, Elem any](ptr *Slice) *Elem {
return AppendPtr(ptr, Zero[Elem]())
}
// Same as global `AppendPtrZero`.
func (self *Slice[A]) AppendPtrZero() *A { return AppendPtrZero(self) }
/*
Returns the first element of the given slice. If the slice is empty, returns the
zero value.
*/
func Head[Slice ~[]Elem, Elem any](val Slice) Elem { return Get(val, 0) }
// Same as global `Head`.
func (self Slice[A]) Head() A { return Head(self) }
/*
Returns a pointer to the first element of the given slice. If the slice is
empty, the pointer is nil.
*/
func HeadPtr[Slice ~[]Elem, Elem any](val Slice) *Elem { return GetPtr(val, 0) }
// Same as global `HeadPtr`.
func (self Slice[A]) HeadPtr() *A { return HeadPtr(self) }
func PopHead[Slice ~[]Elem, Elem any](ptr *Slice) Elem {
if ptr == nil {
return Zero[Elem]()
}
head, tail := Head(*ptr), Tail(*ptr)
*ptr = tail
return head
}
// Same as global `PopHead`.
func (self *Slice[A]) PopHead() A { return PopHead(self) }
/*
Returns the last element of the given slice. If the slice is empty, returns the
zero value.
*/
func Last[Slice ~[]Elem, Elem any](val Slice) Elem { return Get(val, len(val)-1) }
// Same as global `Last`.
func (self Slice[A]) Last() A { return Last(self) }
/*
Returns a pointer to the last element of the given slice. If the slice is empty,
the pointer is nil.
*/
func LastPtr[Slice ~[]Elem, Elem any](val Slice) *Elem { return GetPtr(val, len(val)-1) }
// Same as global `LastPtr`.
func (self Slice[A]) LastPtr() *A { return LastPtr(self) }
/*
Returns the index of the last element of the given slice.
Same as `len(val)-1`. If slice is empty, returns -1.
*/
func LastIndex[Slice ~[]Elem, Elem any](val Slice) int { return len(val) - 1 }
// Same as global `LastIndex`.
func (self Slice[A]) LastIndex() int { return LastIndex(self) }
func PopLast[Slice ~[]Elem, Elem any](ptr *Slice) Elem {
if ptr == nil {
return Zero[Elem]()
}
init, last := Init(*ptr), Last(*ptr)
*ptr = init
return last
}
// Same as global `PopLast`.
func (self *Slice[A]) PopLast() A { return PopLast(self) }
/*
Returns the initial part of the given slice: all except the last value.
If the slice is nil, returns nil.
*/
func Init[Slice ~[]Elem, Elem any](val Slice) Slice {
if len(val) <= 0 {
return val
}
return val[:len(val)-1]
}
// Same as global `Init`.
func (self Slice[A]) Init() Slice[A] { return Init(self) }
/*
Returns the tail part of the given slice: all except the first value.
If the slice is nil, returns nil.
*/
func Tail[Slice ~[]Elem, Elem any](val Slice) Slice {
if len(val) <= 0 {
return val
}
return val[1:]
}
// Same as global `Tail`.
func (self Slice[A]) Tail() Slice[A] { return Tail(self) }
/*
Returns a subslice containing up to N elements from the start.
If there are fewer elements total, returns as many as possible.
*/
func Take[Slice ~[]Elem, Elem any](src Slice, size int) Slice {
return src[:MaxPrim2(0, MinPrim2(size, len(src)))]
}
// Same as global `Take`.
func (self Slice[A]) Take(size int) Slice[A] { return Take(self, size) }
// Returns a subslice excluding N elements from the start.
func Drop[Slice ~[]Elem, Elem any](src Slice, size int) Slice {
return src[MaxPrim2(0, MinPrim2(size, len(src))):]
}
// Same as global `Drop`.
func (self Slice[A]) Drop(size int) Slice[A] { return Drop(self, size) }
/*
Returns a subslice containing only the elements at the start of the slice for
which the given function had contiguously returned `true`. If the function is
nil, it's considered to always return `false`, thus the returned slice is
empty. Also see `TakeLastWhile`.
*/
func TakeWhile[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice {
if fun == nil {
return src[:0]
}
ind := FindIndex(src, func(val Elem) bool { return !fun(val) })
if ind >= 0 {
return src[:ind]
}
return src
}
// Same as global `TakeWhile`.
func (self Slice[A]) TakeWhile(fun func(A) bool) Slice[A] {
return TakeWhile(self, fun)
}
/*
Returns a subslice containing only the elements at the end of the slice for
which the given function had contiguously returned `true`. If the function is
nil, it's considered to always return `false`, thus the returned slice is
empty. Elements are tested from the end of the slice in reverse order, but
the returned subslice has the original element order. Also see `TakeWhile`.
*/
func TakeLastWhile[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice {
if fun == nil {
return src[len(src):]
}
ind := FindLastIndex(src, func(val Elem) bool { return !fun(val) })
if ind >= 0 {
return src[ind+1:]
}
return src
}
// Same as global `TakeLastWhile`.
func (self Slice[A]) TakeLastWhile(fun func(A) bool) Slice[A] {
return TakeLastWhile(self, fun)
}
/*
Returns a subslice excluding the elements at the start of the slice for which
the given function had contiguously returned `true`. If the function is nil,
it's considered to always return `false`, thus the source slice is returned
as-is. Also see `DropLastWhile`.
*/
func DropWhile[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice {
if fun == nil {
return src
}
ind := FindIndex(src, func(val Elem) bool { return !fun(val) })
if ind >= 0 {
return src[ind:]
}
return src[:0]
}
// Same as global `DropWhile`.
func (self Slice[A]) DropWhile(fun func(A) bool) Slice[A] {
return DropWhile(self, fun)
}
/*
Returns a subslice excluding the elements at the end of the slice for which
the given function had contiguously returned `true`. If the function is nil,
it's considered to always return `false`, thus the source slice is returned
as-is. Elements are tested from the end of the slice in reverse order, but
the returned subslice has the original element order. Also see `DropWhile`.
*/
func DropLastWhile[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) bool) Slice {
if fun == nil {
return src
}
ind := FindLastIndex(src, func(val Elem) bool { return !fun(val) })
if ind >= 0 {
return src[:ind+1]
}
return src[:0]
}
// Same as global `DropLastWhile`.
func (self Slice[A]) DropLastWhile(fun func(A) bool) Slice[A] {
return DropLastWhile(self, fun)
}
// Calls the given function for each element of the given slice.
func Each[Slice ~[]Elem, Elem any](val Slice, fun func(Elem)) {
if fun != nil {
for _, val := range val {
fun(val)
}
}
}
// Same as global `Each`.
func (self Slice[A]) Each(val Slice[A], fun func(A)) { Each(self, fun) }
/*
Calls the given function for each element's pointer in the given slice.
The pointer is always non-nil.
*/
func EachPtr[Slice ~[]Elem, Elem any](val Slice, fun func(*Elem)) {
if fun != nil {
for ind := range val {
fun(&val[ind])
}
}
}
// Same as global `EachPtr`.
func (self Slice[A]) EachPtr(fun func(*A)) { EachPtr(self, fun) }
/*
Similar to `Each` but iterates two slices pairwise. If slice lengths don't
match, panics.
*/
func Each2[A, B any](one []A, two []B, fun func(A, B)) {
validateLenMatch(len(one), len(two))
if fun != nil {
for ind := range one {
fun(one[ind], two[ind])
}
}
}
/*
Returns the smallest value from among the inputs, which must be comparable
primitives. Same as built-in `min` (Go 1.21+), expressed as a generic function.
For non-primitives, see `Min`.
*/
func MinPrim[A LesserPrim](val ...A) A { return Fold1(val, MinPrim2[A]) }
/*
Returns the largest value from among the inputs, which must be comparable
primitives. Same as built-in `max` (Go 1.21+), expressed as a generic function.
For non-primitives, see `Max`.
*/
func MaxPrim[A LesserPrim](val ...A) A { return Fold1(val, MaxPrim2[A]) }
/*
Returns the smallest value from among the inputs. For primitive types that don't
implement `Lesser`, see `MinPrim`.
*/
func Min[A Lesser[A]](val ...A) A { return Fold1(val, Min2[A]) }
/*
Returns the largest value from among the inputs. For primitive types that don't
implement `Lesser`, see `MaxPrim`.
*/
func Max[A Lesser[A]](val ...A) A { return Fold1(val, Max2[A]) }
/*
Calls the given function for each element of the given slice and returns the
smallest value from among the results, which must be comparable primitives.
For non-primitives, see `MinBy`.
*/
func MinPrimBy[Src any, Out LesserPrim](src []Src, fun func(Src) Out) Out {
if len(src) <= 0 || fun == nil {
return Zero[Out]()
}
return Fold(src[1:], fun(src[0]), func(acc Out, val Src) Out {
return MinPrim2(acc, fun(val))
})
}
/*
Calls the given function for each element of the given slice and returns the
smallest value from among the results. For primitive types that don't implement
`Lesser`, see `MinPrimBy`.
*/
func MinBy[Src any, Out Lesser[Out]](src []Src, fun func(Src) Out) Out {
if len(src) <= 0 || fun == nil {
return Zero[Out]()
}
return Fold(src[1:], fun(src[0]), func(acc Out, val Src) Out {
return Min2(acc, fun(val))
})
}
/*
Calls the given function for each element of the given slice and returns the
largest value from among the results, which must be comparable primitives.
For non-primitives, see `MaxBy`.
*/
func MaxPrimBy[Src any, Out LesserPrim](src []Src, fun func(Src) Out) Out {
if len(src) <= 0 || fun == nil {
return Zero[Out]()
}
return Fold(src[1:], fun(src[0]), func(acc Out, val Src) Out {
return MaxPrim2(acc, fun(val))
})
}
/*
Calls the given function for each element of the given slice and returns the
largest value from among the results. For primitive types that don't implement
`Lesser`, see `MaxPrimBy`.
*/
func MaxBy[Src any, Out Lesser[Out]](src []Src, fun func(Src) Out) Out {
if len(src) <= 0 || fun == nil {
return Zero[Out]()
}
return Fold(src[1:], fun(src[0]), func(acc Out, val Src) Out {
return Max2(acc, fun(val))
})
}
/*
Calls the given function on each element of the given slice and returns the sum
of all results, combined via `+`.
*/
func Sum[Src any, Out Plusable](src []Src, fun func(Src) Out) Out {
if fun == nil {
return Zero[Out]()
}
return Foldz(src, func(acc Out, src Src) Out { return acc + fun(src) })
}
/*
Counts occurrences elements of the given slice, keyed by calling the given
function for each element, and returning the resulting map. If the function is
nil, returns nil. Compare `Group` which returns `map[Key][]Val` rather than
`map[Key]int`, and `Index` which returns `map[Key]Val`.
*/
func Counts[Slice ~[]Val, Key comparable, Val any](src Slice, fun func(Val) Key) map[Key]int {
if fun == nil {
return nil
}
out := map[Key]int{}
CountsInto(out, src, fun)
return out
}
/*
Counts occurrences elements of the given slice, keyed by calling the given
function for each element, modifying the given map, which must be non-nil if
the slice is non-empty. If the function is nil, does nothing.
*/
func CountsInto[Key comparable, Val any](tar map[Key]int, src []Val, fun func(Val) Key) {
if fun == nil {
return
}
for _, val := range src {
tar[fun(val)]++
}
}
/*
Maps one slice to another. The resulting slice has exactly the same length as
the original. Each element is created by calling the given function on the
corresponding element of the original slice. The name refers to a well-known
functional programming abstraction which doesn't have anything in common with
the Go `map` types. Unlike many other higher-order slice functions, this one
requires a non-nil function; this is a tradeoff for guaranteeing that output
length is always equal to input length.
*/
func Map[A, B any](src []A, fun func(A) B) []B {
if src == nil {
return nil
}
out := make([]B, 0, len(src))
for _, val := range src {
out = append(out, fun(val))
}
return out
}
/*
Similar to `Map` but instead of creating a new slice, appends to an existing
slice.
*/
func MapAppend[
Src ~[]SrcVal,
Tar ~[]TarVal,
SrcVal any,
TarVal any,
](ptr *Tar, src Src, fun func(SrcVal) TarVal) {
if ptr == nil || fun == nil {
return
}
tar := GrowCap(*ptr, len(src))
for _, val := range src {
tar = append(tar, fun(val))
}
*ptr = tar
}
/*
Similar to `Map`, but instead of creating a new slice, mutates the old one in
place by calling the given function on each element.
*/
func MapMut[Slice ~[]Elem, Elem any](src Slice, fun func(Elem) Elem) Slice {
if fun != nil {
for ind := range src {
src[ind] = fun(src[ind])
}
}
return src
}
// Same as global `MapMut`.
func (self Slice[A]) MapMut(fun func(A) A) Slice[A] { return MapMut(self, fun) }
/*
Similar to `Map`, but calls the given function on each element pointer, rather
than on each element. Every pointer is non-nil.
*/
func MapPtr[A, B any](src []A, fun func(*A) B) []B {
if src == nil {
return nil
}
out := make([]B, 0, len(src))
for ind := range src {
out = append(out, fun(&src[ind]))
}
return out
}
/*
Similar to `Map` but iterates two slices pairwise, passing each element pair to
the mapping function. If slice lengths don't match, panics.
*/
func Map2[A, B, C any](one []A, two []B, fun func(A, B) C) []C {
validateLenMatch(len(one), len(two))
if one == nil || two == nil {
return nil
}
out := make([]C, 0, len(one))
for ind := range one {
out = append(out, fun(one[ind], two[ind]))
}
return out
}
// Similar to `Map` but excludes any zero values produced by the given function.
func MapCompact[A, B any](src []A, fun func(A) B) []B {
if fun == nil {
return nil
}
var out []B
for _, val := range src {
val := fun(val)
if !IsZero(val) {
out = append(out, val)
}
}
return out
}
// Similar to `Map` but concats the slices returned by the given function.
func MapFlat[Out ~[]B, A, B any](src []A, fun func(A) Out) Out {
if src == nil {
return nil
}
var out Out
for _, val := range src {
out = append(out, fun(val)...)
}
return out
}
// Similar to `Map` but excludes duplicates.
func MapUniq[A any, B comparable](src []A, fun func(A) B) []B {
if src == nil {
return nil
}
switch len(src) {
case 0:
return []B{}
case 1:
return []B{fun(src[0])}
case 2:
one := fun(src[0])
two := fun(src[1])
if one == two {
return []B{one}
}
return []B{one, two}
default:
set := make(Set[B])
out := make([]B, 0, len(src))
for _, src := range src {
val := fun(src)
if set.Has(val) {
continue
}
set.Add(val)
out = append(out, val)
}
return out
}
}
// Similar to `MapFlat` but excludes duplicates.
func MapFlatUniq[Out ~[]B, A any, B comparable](src []A, fun func(A) Out) Out {
if src == nil {
return nil
}
var out Out
var set Set[B]
for _, src := range src {
for _, val := range fun(src) {
if set.Has(val) {
continue
}
set.Init().Add(val)
out = append(out, val)
}
}
return out
}
/*
Takes a slice and "indexes" it by using keys generated by the given function,
returning the resulting map. If the function is nil, returns nil. Compare
`Group` which returns `map[Key][]Val` rather than `map[Key]Val`.
*/
func Index[Slice ~[]Val, Key comparable, Val any](src Slice, fun func(Val) Key) map[Key]Val {
if fun == nil {
return nil
}
out := make(map[Key]Val, len(src))
IndexInto(out, src, fun)
return out
}
/*
"Indexes" the given slice by adding its values to the given map, keyed by
calling the given function for each value. If the function is nil, does
nothing.
*/
func IndexInto[Key comparable, Val any](tar map[Key]Val, src []Val, fun func(Val) Key) {
if fun == nil {
return
}
for _, val := range src {
tar[fun(val)] = val
}
}
/*
Takes a slice and "indexes" it by converting each element to a key-value pair,
returning the resulting map. If the function is nil or the source slice is
empty, returns nil.
*/
func IndexPair[
Slice ~[]Elem,
Elem any,
Key comparable,
Val any,
](
src Slice, fun func(Elem) (Key, Val),
) map[Key]Val {
if fun == nil || len(src) <= 0 {
return nil
}
out := make(map[Key]Val, len(src))
IndexPairInto(out, src, fun)
return out
}
/*
Takes a slice and "indexes" it by adding key-value pairs to the given map,
making key-value pairs by calling the given function for each element. If the
function is nil or the source slice is empty, does nothing.
*/
func IndexPairInto[Elem any, Key comparable, Val any](
tar map[Key]Val,
src []Elem,
fun func(Elem) (Key, Val),
) {
if fun == nil {
return
}
for _, src := range src {
key, val := fun(src)
tar[key] = val
}
}
/*
Groups the elements of the given slice by using keys generated by the given
function, returning the resulting map. If the function is nil, returns nil.
Compare `Index` which returns `map[Key]Val` rather than `map[Key][]Val`.
*/
func Group[Slice ~[]Val, Key comparable, Val any](src Slice, fun func(Val) Key) map[Key][]Val {