-
Notifications
You must be signed in to change notification settings - Fork 1
/
array.go
813 lines (727 loc) · 18.1 KB
/
array.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
// Package gfn is a Golang library that leverages generics to provide various methods.
package gfn
import "math/rand"
/* @example Contains
gfn.Contains([]int{1, 2, 3}, 2) // true
gfn.Contains([]string{"a", "b", "c"}, "b") // true
gfn.Contains([]time.Duration{time.Second}, time.Second) // true
*/
// Contains returns true if the array contains the value.
func Contains[T comparable](array []T, value T) bool {
for _, v := range array {
if v == value {
return true
}
}
return false
}
/* @example Range
gfn.Range(0, 7) // []int{0, 1, 2, 3, 4, 5, 6}
gfn.Range(3, 8) // []int{3, 4, 3, 6, 7}
gfn.Range(-10, -5) // []int{-10, -9, -8, -7, -6}
*/
// Range function returns a sequence of numbers, starting from start,
// and increments by 1, until end is reached (not included).
func Range[T Int | Uint](start, end T) []T {
if start >= end {
return []T{}
}
res := make([]T, end-start)
for i := 0; i < len(res); i++ {
res[i] = start + T(i)
}
return res
}
/* @example RangeBy
gfn.RangeBy(0, 7, 1) // []int{0, 1, 2, 3, 4, 5, 6}
gfn.RangeBy(0, 8, 2) // []int{0, 2, 4, 6}
gfn.RangeBy(10, 0, -2) // []int{10, 8, 6, 4, 2}
*/
// RangeBy function returns a sequence of numbers, starting from start,
// and increments/decrements by step, until end is reached (not included).
// Zero step panics.
func RangeBy[T Int | Uint](start, end, step T) []T {
if step == 0 {
panic("step must not be zero")
}
if start < end && step > 0 {
res := make([]T, 0, (end-start)/step)
for i := start; i < end; i += step {
res = append(res, i)
}
return res
}
if start > end && step < 0 {
res := make([]T, 0, (end-start)/step)
for i := start; i > end; i += step {
res = append(res, i)
}
return res
}
return []T{}
}
/* @example Shuffle
array := []int{1, 2, 3, 4}
gfn.Shuffle(array)
// array: []int{2, 1, 4, 3} or other random order
*/
// Shuffle randomizes the order of elements by using Fisher–Yates algorithm
func Shuffle[T any](array []T) {
for i := range array {
j := rand.Intn(i + 1)
array[i], array[j] = array[j], array[i]
}
}
/* @example Equal
gfn.Equal([]int{1, 2, 3}, []int{1, 2, 3}) // true
gfn.Equal([]string{"a", "c", "b"}, []string{"a", "b", "c"}) // false
*/
// Equal returns true if two arrays are equal. Two arrays are considered equal
// if both are nil, or if their lengths are equal and their elements are equal.
// Elements are compared using == operator.
func Equal[T comparable](a, b []T) bool {
if len(a) != len(b) {
return false
}
for i, aa := range a {
if aa != b[i] {
return false
}
}
return true
}
/* @example EqualBy
a := []int{1, 2, 3, 4, 5}
b := []rune{'a', 'b', 'c', 'd', 'e'}
gfn.EqualBy(a, b, func(aa int, bb rune) bool {
return (aa - 1) == int(bb-'a')
}) // true
*/
// EqualBy returns true if two arrays are equal by comparing their elements
// using the given function.
func EqualBy[T1, T2 any](a []T1, b []T2, fn func(T1, T2) bool) bool {
if len(a) != len(b) {
return false
}
for i, aa := range a {
if !fn(aa, b[i]) {
return false
}
}
return true
}
/* @example ToSet
gfn.ToSet([]int{0, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5})
// map[int]struct{}{0: {}, 1: {}, 2: {}, 3: {}, 4: {}, 5: {}}
*/
// ToSet converts an array to a set.
func ToSet[T comparable](array []T) map[T]struct{} {
res := make(map[T]struct{})
for _, v := range array {
res[v] = struct{}{}
}
return res
}
/* @example IsSortedBy
gfn.IsSortedBy([]int{2, 2, 1, 1, -1, -1}, func(a, b int) bool { return a >= b })
// true
*/
// IsSortedBy returns true if the array is sorted in the given order.
// The order function should return true if a1 is ok to be placed before a2.
func IsSortedBy[T any](array []T, order func(a1, a2 T) bool) bool {
for i := 0; i < len(array)-1; i++ {
if !order(array[i], array[i+1]) {
return false
}
}
return true
}
/* @example IsSorted
gfn.IsSorted([]int{1, 2, 3, 4}) // true
*/
// IsSorted returns true if the array is sorted in ascending order.
func IsSorted[T Int | Uint | Float | ~string](array []T) bool {
for i := 0; i < len(array)-1; i++ {
if array[i] > array[i+1] {
return false
}
}
return true
}
/* @example Counter
gfn.Counter([]int{1, 2, 2, 2, 2}) // map[int]int{1: 1, 2: 4}
*/
// Counter returns a map of values and their counts.
func Counter[T comparable](array []T) map[T]int {
res := make(map[T]int)
for _, v := range array {
res[v]++
}
return res
}
/* @example CounterBy
type Employee struct {
name string
department string
}
employees := []Employee{
{"Alice", "Accounting"},
{"Dave", "Engineering"},
{"Eve", "Engineering"},
}
gfn.CounterBy(employees, func(e Employee) string {
return e.department
}) // map[string]int{"Accounting": 1, "Engineering": 2}
*/
// CounterBy returns a map of values and their counts. The values are
// calculated by the given function.
func CounterBy[T any, U comparable](array []T, fn func(T) U) map[U]int {
res := make(map[U]int)
for _, v := range array {
res[fn(v)]++
}
return res
}
/* @example Zip
gfn.Zip([]int{1, 2, 3}, []string{"a", "b", "c"})
// []gfn.Pair[int, string]{
// {First: 1, Second: "a"},
// {First: 2, Second: "b"},
// {First: 3, Second: "c"}
// }
*/
// Zip returns a sequence of pairs built from the elements of two arrays.
func Zip[T, U any](a []T, b []U) []Pair[T, U] {
l := Min(len(a), len(b))
res := make([]Pair[T, U], l)
for i := 0; i < l; i++ {
res[i] = Pair[T, U]{a[i], b[i]}
}
return res
}
/* @example Unzip
pairs := []gfn.Pair[int, string]{
{First: 1, Second: "a"},
{First: 2, Second: "b"},
{First: 3, Second: "c"},
}
gfn.Unzip(len(pairs), func(i int) (int, string) {
return pairs[i].First, pairs[i].Second
})
// ([]int{1, 2, 3}, []string{"a", "b", "c"})
*/
// Unzip returns two arrays built from the elements of a sequence of pairs.
func Unzip[T, U any](n int, unzipFn func(i int) (T, U)) ([]T, []U) {
if n < 0 {
panic("negative length")
}
a := make([]T, n)
b := make([]U, n)
for i := 0; i < n; i++ {
a[i], b[i] = unzipFn(i)
}
return a, b
}
/* @example Sample
gfn.Sample([]int{1, 2, 3, 4, 5}, 3) // []int{3, 1, 5} or other random choices.
*/
// Sample returns a random sample of n elements from an array. Every position in
// the array are at most selected once. n should be less or equal to len(array).
func Sample[T any](array []T, n int) []T {
if n < 0 {
panic("negative length")
}
if n > len(array) {
panic("sample size larger than array length")
}
indexes := Range(0, n)
Shuffle(indexes)
res := make([]T, n)
for i := 0; i < n; i++ {
res[i] = array[indexes[i]]
}
return res
}
/* @example Uniq
gfn.Uniq([]int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4}) // []int{1, 2, 3, 4}
*/
// Uniq returns an array with all duplicates removed.
func Uniq[T comparable](array []T) []T {
res := []T{}
seen := make(map[T]struct{})
for _, v := range array {
if _, ok := seen[v]; !ok {
res = append(res, v)
seen[v] = struct{}{}
}
}
return res
}
/* @example UniqBy
type Employee struct {
name string
department string
}
employees := []Employee{
{"Alice", "Accounting"},
{"Bob", "Accounting"},
{"Cindy", "Engineering"},
{"Dave", "Engineering"},
}
gfn.UniqBy(employees, func(e Employee) string {
return e.department
})
// []Employee{{"Alice", "Accounting"}, {"Cindy", "Engineering"}}
*/
// UniqBy returns an array with all duplicates removed by applying a function to each element.
func UniqBy[T any, U comparable](array []T, fn func(T) U) []T {
res := []T{}
seen := make(map[U]struct{})
for _, v := range array {
value := fn(v)
if _, ok := seen[value]; !ok {
res = append(res, v)
seen[value] = struct{}{}
}
}
return res
}
/* @example Union
gfn.Union([]int{1, 2, 3}, []int{2, 3, 4}, []int{3, 4, 5})
// []int{1, 2, 3, 4, 5}
*/
// Union returns an array with all duplicates removed from multiple arrays.
func Union[T comparable](arrays ...[]T) []T {
res := []T{}
seen := make(map[T]struct{})
for _, array := range arrays {
for _, v := range array {
if _, ok := seen[v]; !ok {
res = append(res, v)
seen[v] = struct{}{}
}
}
}
return res
}
/* @example UnionBy
type Employee struct {
name string
department string
}
group1 := []Employee{
{"Alice", "Accounting"},
{"Bob", "Accounting"},
{"Cindy", "Engineering"},
}
group2 := []Employee{
{"Alice", "Accounting"},
{"Cindy", "Engineering"},
{"Dave", "Engineering"},
{"Eve", "Engineering"},
}
gfn.UnionBy(func(e Employee) string { return e.name }, group1, group2)
// []Employee{
// {"Alice", "Accounting"},
// {"Bob", "Accounting"},
// {"Cindy", "Engineering"},
// {"Dave", "Engineering"},
// {"Eve", "Engineering"},
// }
*/
// UnionBy returns an array with all duplicates removed from multiple arrays
// by applying a function to each element.
func UnionBy[T any, U comparable](fn func(T) U, arrays ...[]T) []T {
res := []T{}
seen := make(map[U]struct{})
for _, array := range arrays {
for _, v := range array {
value := fn(v)
if _, ok := seen[value]; !ok {
res = append(res, v)
seen[value] = struct{}{}
}
}
}
return res
}
/* @example Copy
gfn.Copy([]int{1, 2, 3}) // []int{1, 2, 3}
array := []int{1, 2, 3, 4, 5, 6}
gfn.Copy(array[2:])
// []int{3, 4, 5, 6}
*/
// Copy returns a new array that is a shallow copy of the original array.
func Copy[T any](array []T) []T {
res := make([]T, len(array))
copy(res, array)
return res
}
/* @example Difference
gfn.Difference([]int{1, 2, 3, 4}, []int{2, 4}) // []int{1, 3}
*/
// Difference returns a new array that is a copy of the original array,
// removing all occurrences of any item that also appear in others.
// The order is preserved from the original array.
func Difference[T comparable](array []T, others ...[]T) []T {
res := Copy(array)
for _, other := range others {
m := ToSet(other)
res = Filter(res, func(v T) bool {
_, ok := m[v]
return !ok
})
}
return res
}
/* @example DifferenceBy
type Data struct {
value int
}
data1 := []Data{{1}, {3}, {2}, {4}, {5}, {2}}
data2 := []Data{{3}, {4}, {5}}
gfn.DifferenceBy(func(d Data) int { return d.value }, data1, data2)
// []Data{{1}, {2}, {2}}
*/
// DifferenceBy returns a new array that is a copy of the original array,
// removing all occurrences of any item that also appear in others. The occurrences
// are determined by applying a function to each element.
func DifferenceBy[T any, U comparable](fn func(T) U, array []T, others ...[]T) []T {
res := make([]Pair[U, T], len(array))
for i, v := range array {
res[i] = Pair[U, T]{fn(v), v}
}
for _, other := range others {
seen := map[U]struct{}{}
for _, v := range other {
seen[fn(v)] = struct{}{}
}
res = Filter(res, func(p Pair[U, T]) bool {
_, ok := seen[p.First]
return !ok
})
}
return Map(res, func(p Pair[U, T]) T {
return p.Second
})
}
/* @example Fill
array := make([]bool, 5)
gfn.Fill(array, true)
// []bool{true, true, true, true, true}
// you can control the start and end index by using the slice
array2 := make([]int, 5)
gfn.Fill(array2[2:], 100)
// []int{0, 0, 100, 100, 100}
*/
// Fill sets all elements of an array to a given value.
// You can control the start and end index by using the slice.
func Fill[T any](array []T, value T) {
for i := range array {
array[i] = value
}
}
/* @example Count
gfn.Count([]int{1, 2, 2, 2, 5, 6}, 2) // 3
*/
// Count returns the number of occurrences of a value in an array.
func Count[T comparable](array []T, value T) int {
res := 0
for _, v := range array {
if v == value {
res++
}
}
return res
}
/* @example CountBy
type Employee struct {
name string
department string
}
employees := []Employee{
{"Alice", "Accounting"},
{"Cindy", "Engineering"},
{"Dave", "Engineering"},
{"Eve", "Engineering"},
}
gfn.CountBy(employees, func(e Employee) bool {
return e.department == "Engineering"
}) // 3
*/
// CountBy returns the number of elements in an array that satisfy a predicate.
func CountBy[T any](array []T, fn func(T) bool) int {
res := 0
for _, v := range array {
if fn(v) {
res++
}
}
return res
}
/* @example GroupBy
array := []int{1, 2, 3, 4, 5, 6, 7, 8}
groups := gfn.GroupBy(array, func(i int) string {
if i%2 == 0 {
return "even"
}
return "odd"
})
// map[string][]int{
// "even": []int{2, 4, 6, 8},
// "odd": []int{1, 3, 5, 7},
// }
*/
// GroupBy generate a map of arrays by grouping the elements of an array
// according to a given function.
func GroupBy[T any, K comparable](array []T, groupFn func(T) K) map[K][]T {
res := make(map[K][]T)
for _, v := range array {
k := groupFn(v)
res[k] = append(res[k], v)
}
return res
}
/* @example IndexOf
gfn.IndexOf([]int{1, 2, 3, 4}, 3) // 2
gfn.IndexOf([]int{1, 2, 3, 4}, 5) // -1
*/
// IndexOf returns the index of the first occurrence of a value in an array,
// or -1 if not found.
func IndexOf[T comparable](array []T, value T) int {
for i, v := range array {
if v == value {
return i
}
}
return -1
}
/* @example LastIndexOf
gfn.LastIndexOf([]int{3, 3, 3, 4}, 3) // 2
gfn.LastIndexOf([]int{1, 2, 3, 4}, 5) // -1
*/
// LastIndexOf returns the index of the last occurrence of a value in an array,
// or -1 if not found.
func LastIndexOf[T comparable](array []T, value T) int {
for i := len(array) - 1; i >= 0; i-- {
if array[i] == value {
return i
}
}
return -1
}
/* @example Reverse
array := []int{1, 2, 3, 4}
gfn.Reverse(array)
// []int{4, 3, 2, 1}
*/
// Reverse reverses an array in place.
func Reverse[T any](array []T) {
for i, j := 0, len(array)-1; i < j; i, j = i+1, j-1 {
array[i], array[j] = array[j], array[i]
}
}
/* @example All
gfn.All([]int{1, 2, 3, 4}, func(i int) bool {
return i > 0
}
// true
*/
// All returns true if all elements in an array pass a given test.
func All[T any](array []T, fn func(T) bool) bool {
for _, v := range array {
if !fn(v) {
return false
}
}
return true
}
/* @example Any
gfn.Any([]int{1, 2, 3, 4}, func(i int) bool {
return i > 3
}
// true
*/
// Any returns true if at least one element in an array passes a given test.
func Any[T any](array []T, fn func(T) bool) bool {
for _, v := range array {
if fn(v) {
return true
}
}
return false
}
/* @example Concat
gfn.Concat([]int{1, 2}, []int{3, 4}) // []int{1, 2, 3, 4}
*/
// Concat returns a new array that is the result of joining two or more arrays.
func Concat[T any](arrays ...[]T) []T {
var res []T
for _, array := range arrays {
res = append(res, array...)
}
return res
}
/* @example Find
value, index := gfn.Find([]string{"a", "ab", "abc"}, func(s string) bool {
return len(s) > 1
})
// "ab", 1
*/
// Find returns the first element in an array that passes a given test and corresponding index.
// Index of -1 is returned if no element passes the test.
func Find[T any](array []T, fn func(T) bool) (T, int) {
for i, v := range array {
if fn(v) {
return v, i
}
}
var res T
return res, -1
}
/* @example FindLast
value, index := gfn.FindLast([]string{"a", "ab", "abc"}, func(s string) bool {
return len(s) > 1
})
// "abc", 2
*/
// FindLast returns the last element in an array that passes a given test and corresponding index.
// Index of -1 is returned if no element passes the test.
func FindLast[T any](array []T, fn func(T) bool) (T, int) {
for i := len(array) - 1; i >= 0; i-- {
if fn(array[i]) {
return array[i], i
}
}
var res T
return res, -1
}
/* @example Remove
gfn.Remove([]int{1, 2, 3, 4, 2, 3, 2, 3}, 2, 3) // []int{1, 4}
*/
// Remove removes all elements from an array that equal to given values.
func Remove[T comparable](array []T, values ...T) []T {
res := []T{}
valueSet := ToSet(values)
for _, v := range array {
_, ok := valueSet[v]
if !ok {
res = append(res, v)
}
}
return res
}
/* @example Intersection
arr1 := []int{1, 2, 3, 4, 5}
arr2 := []int{2, 3, 4, 5, 6}
arr3 := []int{5, 4, 3, 2}
arr4 := []int{2, 3}
gfn.Intersection(arr1, arr2, arr3, arr4) // []int{2, 3}
*/
// Intersection returns a new array that is the intersection of two or more arrays.
func Intersection[T comparable](arrays ...[]T) []T {
if len(arrays) <= 1 {
panic("requires at least 2 arrays")
}
res := Uniq(arrays[0])
for _, arr := range arrays[1:] {
set := ToSet(arr)
res = Filter(res, func(v T) bool {
_, ok := set[v]
return ok
})
}
return res
}
/* @example IntersectionBy
type Data struct {
value int
}
data1 := []Data{{1}, {3}, {2}, {4}, {5}}
data2 := []Data{{2}, {3}}
gfn.IntersectionBy(func(d Data) int { return d.value }, data1, data2)
// []Data{{3}, {2}}
*/
// IntersectionBy returns a new array that is the intersection of two or more arrays,
// where intersection is determined by a given function.
func IntersectionBy[T any, U comparable](fn func(T) U, arrays ...[]T) []T {
if len(arrays) <= 1 {
panic("requires at least 2 arrays")
}
// make unique pair of array[0]
var res []Pair[U, T]
seen := map[U]struct{}{}
for _, v := range arrays[0] {
key := fn(v)
if _, ok := seen[key]; !ok {
res = append(res, Pair[U, T]{key, v})
seen[key] = struct{}{}
}
}
// filter by seen
for _, arr := range arrays[1:] {
seen = map[U]struct{}{}
for _, v := range arr {
seen[fn(v)] = struct{}{}
}
res = Filter(res, func(p Pair[U, T]) bool {
_, ok := seen[p.First]
return ok
})
}
return Map(res, func(p Pair[U, T]) T {
return p.Second
})
}
/* @example Repeat
gfn.Repeat([]int{1, 2, 3}, 3) // []int{1, 2, 3, 1, 2, 3, 1, 2, 3}
*/
// Repeat returns a new array that is the result of repeating an array
// a given number of times.
func Repeat[T any](array []T, repeat int) []T {
if repeat < 0 {
panic("repeat must be greater or equal to 0")
}
if repeat == 0 {
return []T{}
}
if repeat == 1 {
return Copy(array)
}
res := make([]T, len(array)*repeat)
for i := 0; i < repeat; i++ {
copy(res[i*len(array):], array)
}
return res
}
/* @example ForEach
sum := 0
gfn.ForEach([]int{1, 2, 3}, func(i int) {
sum += i
})
// sum == 6
*/
// ForEach executes a provided function once for each array element.
func ForEach[T any](array []T, fn func(value T)) {
for _, v := range array {
fn(v)
}
}
/* @example Chunk
gfn.Chunk([]int{1, 2, 3, 4, 5}, 2) // [][]int{{1, 2}, {3, 4}, {5}}
*/
// Chunk splits an array into chunks of given size.
func Chunk[T any](array []T, size int) [][]T {
if size <= 0 {
panic("size must be greater than 0")
}
var res [][]T
for i := 0; i < len(array); i += size {
end := i + size
if end > len(array) {
end = len(array)
}
res = append(res, array[i:end])
}
return res
}