-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
986 lines (925 loc) 路 33.3 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
package slice
import (
"fmt"
"math/rand"
"reflect"
"sort"
)
// Slice is a generic list-like struct that allows for the manipulation and traversal of elements by numeric index.
// It is parameterized with the type T, allowing it to work with slices of any data type.
//
// Example usage:.
//
// // Create a Slice of integers.
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
//
// // Append values to the Slice.
// s.Append(6, 7, 8).
//
// // Check if a value exists in the Slice.
// contains := s.Contains(3) // contains is true.
//
// // Find the index of the first element that satisfies a condition.
// index, found := s.FindIndex(func(value int) bool {.
// return value > 4.
// }).
//
// // Delete an element by index.
// s.Delete(2) // Removes the element at index 2.
//
// // Iterate over the elements and perform an operation on each.
// s.Each(func(i int, value int) {.
// fmt.Printf("Element %d: %d\n", i, value).
// }).
//
// This type provides a set of methods for common Slice operations and is designed to be generic for flexibility.
type Slice[T any] []T
// Append appends the specified values to the end of the Slice and returns a pointer to the modified Slice.
// It extends the Slice by adding the provided values to the end, updating the Slice in place.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// s.Append(4, 5) // s is now [1, 2, 3, 4, 5].
func (slice *Slice[T]) Append(values ...T) *Slice[T] {
*slice = append(*slice, values...)
return slice
}
// AppendFunc appends selected elements to the end of the Slice based on a provided condition.
// It iterates over the specified values, invoking the provided function for each element.
// If the function returns true for an element, that element is added to the end of the Slice.
//
// Example:.
//
// s := &slice.Slice[int]{}.
// s.AppendFunc(func(i int, value int) bool {.
// return value%2 == 0 // Append even numbers to the Slice.
// }, 1, 2, 3, 4, 5).
//
// After this operation, s will contain [2, 4].
//
// This method modifies the original Slice and returns a pointer to the modified Slice.
func (slice *Slice[T]) AppendFunc(fn func(i int, value T) bool, values ...T) *Slice[T] {
var s Slice[T]
for i, value := range values {
if ok := fn(i, value); ok {
s = append(s, value)
}
}
*slice = append(*slice, s...)
return slice
}
// AppendLength appends the specified values to the end of the Slice and returns the length of the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// length := s.AppendLength(4, 5) // s is now [1, 2, 3, 4, 5], length is 5.
func (slice *Slice[T]) AppendLength(values ...T) int {
return slice.Append(values...).Length()
}
// Bounds checks if the given integer index is within the valid range of indices for the Slice.
// It returns true if the index is greater than or equal to 0 and less than the length of the slice, indicating that the index is within bounds.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// inBounds := s.Bounds(1) // inBounds is true.
// outOfBounds := s.Bounds(5) // outOfBounds is false.
func (slice *Slice[T]) Bounds(i int) bool {
return i >= 0 && i < slice.Length()
}
// Clone creates and returns a new slice that contains the same elements as the original slice.
// The original slice remains unchanged.
//
// Example:.
//
// numbers := slice.Slice[int]{1, 2, 3, 4, 5}.
// clonedSlice := numbers.Clone().
// // clonedSlice: [1, 2, 3, 4, 5].
func (slice *Slice[T]) Clone() *Slice[T] {
s := *slice
return &s
}
// Concatenate merges the elements from the argument Slice to the tail of the receiver Slice and returns the modified Slice.
// If the provided Slice (s) is not nil, it appends its elements to the end of the receiver slice, updating the Slice in place.
//
// Example:.
//
// s1 := &slice.Slice[int]{1, 2, 3}.
// s2 := &slice.Slice[int]{4, 5}.
// s1.Concatenate(s2) // s1 is now [1, 2, 3, 4, 5].
func (slice *Slice[T]) Concatenate(s *Slice[T]) *Slice[T] {
if s != nil {
slice.Append((*s)...)
}
return slice
}
// ConcatenateFunc appends elements from the provided Slice (s) to the end of the receiver slice, based on the result of a filtering function.
//
// Example:.
//
// s1 := &slice.Slice[int]{1, 2, 3}.
// s2 := &slice.Slice[int]{4, 5, 6}.
// s1.ConcatenateFunc(s2, func(i int, value int) bool {.
// return value%2 == 0.
// }) // s1 is now [1, 2, 3, 4, 6].
func (slice *Slice[T]) ConcatenateFunc(s *Slice[T], fn func(i int, value T) bool) *Slice[T] {
if s != nil {
slice.AppendFunc(fn, *s...)
}
return slice
}
// ConcatenateLength merges the elements from the argument Slice to the tail of the receiver Slice and returns the length of the modified Slice.
//
// Example:.
//
// s1 := &slice.Slice[int]{1, 2, 3}.
// s2 := &slice.Slice[int]{4, 5}.
// length := s1.ConcatenateLength(s2) // s1 is now [1, 2, 3, 4, 5], length is 5.
func (slice *Slice[T]) ConcatenateLength(s *Slice[T]) int {
return slice.Concatenate(s).Length()
}
// Contains iterates over the elements of the Slice and compares each element with the provided value.
// If a matching element is found, it returns true; otherwise, it returns false.
//
// Example:.
//
// s := &slice.Slice[string]{"apple", "banana", "cherry"}.
// containsBanana := s.Contains("banana") // containsBanana is true.
func (slice *Slice[T]) Contains(value T) bool {
for _, v := range *slice {
if reflect.DeepEqual(v, value) {
return true
}
}
return false
}
// ContainsMany checks if multiple values exist in the Slice and returns a boolean Slice indicating their presence.
// It takes a variadic number of values and checks each of them against the elements in the Slice.
// The returned boolean Slice will have 'true' at the corresponding index if the value is found, 'false' otherwise.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// result := s.ContainsMany(2, 4, 6) // result will be [true, true, false].
func (slice *Slice[T]) ContainsMany(values ...T) *Slice[bool] {
s := &Slice[bool]{}
for _, value := range values {
s.Append(slice.Contains(value))
}
return s
}
// Delete removes the element at the specified index from the slice, if the index is within bounds.
// It modifies the Slice in place by removing the element at the given index and returns a pointer to the modified Slice.
// If the index is out of bounds, it does not modify the Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// s.Delete(2) // s is now [1, 2, 4, 5].
func (slice *Slice[T]) Delete(i int) *Slice[T] {
if slice.Bounds(i) {
slice.DeleteUnsafe(i)
}
return slice
}
// DeleteFunc removes elements from the Slice based on the provided predicate function.
// It iterates over each element of the Slice and applies the given function to each element.
// If the function returns true for an element, that element is removed from the slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// even := func(i int, value int) bool { return value%2 == 0 }.
// s.DeleteFunc(even).
// // 's' will contain [1, 3, 5] after removing even elements.
func (slice *Slice[T]) DeleteFunc(fn func(i int, value T) bool) *Slice[T] {
length := slice.Length()
for i := 0; i < length; i++ {
if fn(i, slice.Fetch(i)) {
// Delete the element at index i.
slice.DeleteUnsafe(i)
i-- // Adjust the index after deletion.
length-- // Update the length.
}
}
return slice
}
// DeleteLength removes the element at the specified index from the slice, if the index is within bounds, and returns the new length of the modified Slice.
// It modifies the Slice in place by removing the element at the given index and returns the new length of the Slice.
// If the index is out of bounds, it does not modify the Slice and returns the current length.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// newLength := s.DeleteLength(2) // s is now [1, 2, 4, 5], newLength is 4.
func (slice *Slice[T]) DeleteLength(i int) int {
return slice.Delete(i).Length()
}
// DeleteOK removes the element at the specified index from the Slice if the index is within bounds and returns the result of the transaction.
// It modifies the Slice in place by removing the element at the given index and returns true if the deletion was successful.
// If the index is out of bounds, it does not modify the Slice and returns false.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// deleted := s.DeleteOK(2) // s is now [1, 2, 4, 5], deleted is true.
func (slice *Slice[T]) DeleteOK(i int) bool {
if slice.Bounds(i) {
slice.Delete(i)
return true
}
return false
}
// DeleteUnsafe deletes the element from the specified index without bounds checking.
// It removes the element at the given index without checking whether the index is within the bounds of the slice.
// Be cautious when using this method to avoid index out-of-range errors.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// s.DeleteUnsafe(2).
// // The Slice becomes [1, 2, 4, 5] with the element at index 2 (value 3) removed.
func (slice *Slice[T]) DeleteUnsafe(i int) *Slice[T] {
*slice = append((*slice)[:i], (*slice)[i+1:]...)
return slice
}
// Each executes a provided function once for each element in the Slice and returns the Slice.
// It iterates over each element of the slice, invoking the provided function for each element, and returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[string]{"apple", "banana", "cherry"}.
// s.Each(func(i int, value string) {.
// fmt.Printf("Element %d: %s\n", i, value).
// }).
func (slice *Slice[T]) Each(fn func(i int, value T)) *Slice[T] {
slice.EachBreak(func(i int, value T) bool {
fn(i, value)
return true
})
return slice
}
// EachBreak executes a provided function once for each element in the Slice with an optional break when the function returns false.
// It iterates over each element of the slice, invoking the provided function for each element. If the function returns false, the iteration stops.
// It returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// s.EachBreak(func(i int, value int) bool {.
// fmt.Printf("Element %d: %d\n", i, value).
// return i < 3 // Stop iteration when i is less than 3.
// }).
func (slice *Slice[T]) EachBreak(fn func(i int, value T) bool) *Slice[T] {
for i, v := range *slice {
if !fn(i, v) {
break
}
}
return slice
}
// EachReverse executes a provided function once for each element in the reverse order they are stored in the Slice.
// It iterates over each element of the Slice in reverse order, invoking the provided function for each element, and returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// s.EachReverse(func(i int, value int) {.
// fmt.Printf("Element %d: %d\n", i, value).
// }).
func (slice *Slice[T]) EachReverse(fn func(i int, value T)) *Slice[T] {
slice.EachReverseBreak(func(i int, value T) bool {
fn(i, value)
return true
})
return slice
}
// EachReverseBreak executes a provided function once for each element in the reverse order they are stored in the Slice with an optional break when the function returns false.
// It iterates over each element of the Slice in reverse order, invoking the provided function for each element. If the function returns false, the iteration stops.
// It returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// s.EachReverseBreak(func(i int, value int) bool {.
// fmt.Printf("Element %d: %d\n", i, value).
// return i > 2 // Stop iteration when i is greater than 2.
// }).
func (slice *Slice[T]) EachReverseBreak(fn func(i int, value T) bool) *Slice[T] {
for i := slice.Length() - 1; i >= 0; i-- {
// If the function returns false, break out of the loop.
if !fn(i, (*slice)[i]) {
break
}
}
return slice
}
// Equal checks if the current Slice is equal to another Slice by comparing their elements.
// It returns true if the two slices have the same length and all corresponding elements are deeply equal.
//
// Example:.
//
// s1 := slice.Slice[int]{1, 2, 3}.
// s2 := slice.Slice[int]{1, 2, 3}.
// equal := s1.Equal(s2) // true.
func (slice *Slice[T]) Equal(s *Slice[T]) bool {
return slice.EqualFunc(s, func(i int, value1, value2 T) bool {
return reflect.DeepEqual(value1, value2)
})
}
// EqualFunc checks if the current Slice is equal to another Slice by applying a custom comparison function to their elements.
// It returns true if the two slices have the same length and the custom comparison function returns true for all corresponding elements.
//
// Example:.
//
// s1 := slice.Slice[int]{1, 2, 3}.
// s2 := slice.Slice[int]{2, 4, 6}.
// customEqual := func(i int, value1, value2 int) bool {.
// return value1*2 == value2.
// }.
// equal := s1.EqualFunc(s2, customEqual) // true.
func (slice *Slice[T]) EqualFunc(s *Slice[T], fn func(i int, value1, value2 T) bool) bool {
var ok bool
if slice.Length() != s.Length() {
return false
}
slice.EachBreak(func(i int, value T) bool {
ok = fn(i, value, s.Fetch(i))
return ok
})
return ok
}
// Fetch retrieves the element held at the specified index in the Slice.
//
// Example:.
//
// s := &slice.Slice[string]{"apple", "banana", "cherry"}.
// fruit := s.Fetch(1).
// // fruit will be "banana".
func (slice *Slice[T]) Fetch(i int) T {
v, _ := slice.Get(i)
return v
}
// FetchLength retrieves the element held at the specified index in the Slice and the length of the Slice.
// It returns the element at the specified index and the length of the Slice.
//
// Example:.
//
// s := &slice.Slice[int]{10, 20, 30, 40, 50}.
// value, length := s.FetchLength(2).
// // value will be 30.
// // length will be 5.
func (slice *Slice[T]) FetchLength(i int) (T, int) {
return slice.Fetch(i), slice.Length()
}
// Filter creates a new Slice containing only the elements that satisfy the given predicate function.
// It iterates over the elements of the Slice and applies the predicate function to each element.
// Elements for which the predicate returns true are included in the new Slice, and others are excluded.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// filtered := s.Filter(func(x int) bool {.
// return x%2 == 0 // Keep only even numbers.
// }).
// // filtered will be &Slice[int]{2, 4}.
func (slice *Slice[T]) Filter(fn func(i int, value T) bool) *Slice[T] {
s := &Slice[T]{}
slice.Each(func(i int, value T) {
if fn(i, value) {
s.Append(value)
}
})
return s
}
// FindIndex finds the index of the first element that satisfies the given predicate function.
// It returns the index of the first matching element and true if found; otherwise, it returns -1 and false.
//
// Example:.
//
// s := &slice.Slice[string]{"apple", "banana", "cherry"}.
// index, found := s.FindIndex(func(fruit string) bool {.
// return fruit == "banana".
// }).
// // index will be 1.
// // found will be true.
func (slice *Slice[T]) FindIndex(fn func(value T) bool) (int, bool) {
var index int
var ok bool
slice.EachBreak(func(i int, value T) bool {
index = i
ok = fn(value)
if !ok {
index = -1
}
return !ok
})
return index, ok
}
// Get retrieves the element held at the specified index in the Slice and a boolean indicating if it was successfully retrieved.
// It returns the element at the specified index and a boolean indicating whether the element was successfully retrieved.
//
// Example:.
//
// s := &slice.Slice[float64]{3.14, 2.71, 1.61}.
// value, ok := s.Get(1).
// // value will be 2.71.
// // ok will be true.
func (slice *Slice[T]) Get(i int) (T, bool) {
var (
ok = slice.Bounds(i)
v T
)
if ok {
v = (*slice)[i]
}
return v, ok
}
// GetLength retrieves the element held at the specified index in the slice, the length of the slice, and a boolean indicating if it was successfully retrieved.
// It returns the element at the specified index, the length of the slice, and a boolean indicating whether the element was successfully retrieved.
//
// Example:.
//
// s := &slice.Slice[int]{10, 20, 30, 40, 50}.
// value, length, ok := s.GetLength(2).
// // value will be 30.
// // length will be 5.
// // ok will be true.
func (slice *Slice[T]) GetLength(i int) (T, int, bool) {
v, ok := slice.Get(i)
l := slice.Length()
return v, l, ok
}
// IsEmpty returns whether the Slice is empty.
// It returns true if the Slice is empty (length is zero), otherwise false.
//
// Example:.
//
// s := &slice.Slice[int]{}.
// isEmpty := s.IsEmpty() // isEmpty will be true.
func (slice *Slice[T]) IsEmpty() bool {
return slice.Length() == 0
}
// IsPopulated returns whether the Slice is populated.
// It returns true if the Slice is not empty (length is greater than zero), otherwise false.
//
// Example:.
//
// s := &slice.Slice[int]{10, 20, 30}.
// isPopulated := s.IsPopulated() // isPopulated will be true.
func (slice *Slice[T]) IsPopulated() bool {
return !slice.IsEmpty()
}
// Length returns the number of elements in the Slice.
//
// Example:.
//
// s := &slice.Slice[int]{10, 20, 30, 40, 50}.
// length := s.Length() // length will be 5.
func (slice *Slice[T]) Length() int {
return len(*slice)
}
// Make empties the slice, sets the new Slice to the length of n, and returns the modified Slice.
// It replaces the existing Slice with a new Slice of the specified length (n) and returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{10, 20, 30}.
// s.Make(3) // s will be an empty Slice of length 3.
func (slice *Slice[T]) Make(i int) *Slice[T] {
// Create a new slice of the specified length i.
*slice = make(Slice[T], i)
return slice
}
// MakeEach empties the slice, sets the new Slice to the length of n, and populates it by performing a for-each loop on the provided values.
// Finally, it returns a pointer to the modified Slice.
// It replaces the existing Slice with a new Slice of the specified length (n) and populates it by performing a for-each loop on the provided values.
//
// Example:.
//
// s := &slice.Slice[int]{}.
// s.MakeEach(10, 20, 30) // s will be a Slice containing {10, 20, 30}.
func (slice *Slice[T]) MakeEach(v ...T) *Slice[T] {
return slice.Make(len(v)).Each(func(i int, _ T) {
// Replace each element in the new slice with the corresponding value from the provided values.
slice.Replace(i, v[i])
})
}
// MakeEachReverse empties the slice, sets the new Slice to the length of n, and performs an inverse for-each loop on the provided values,.
// inserting each entry at the appropriate index before returning the modified Slice.
// It replaces the existing Slice with a new Slice of the specified length (n) and populates it by performing an inverse for-each loop on the provided values.
//
// Example:.
//
// s := &slice.Slice[int]{}.
// s.MakeEachReverse(10, 20, 30) // s will be a Slice containing {30, 20, 10}.
func (slice *Slice[T]) MakeEachReverse(values ...T) *Slice[T] {
currentOffset := 0
return slice.Make(len(values)).EachReverse(func(i int, _ T) {
slice.Replace(currentOffset, values[i])
currentOffset++
})
}
// Map applies the provided function to each element in the slice and creates a new slice containing the modified elements.
// It returns a new Slice[T] containing the transformed elements. The original slice is not modified.
//
// Example:.
//
// numbers := slice.Slice[int]{1, 2, 3, 4, 5}.
// squared := numbers.Map(func(i int, value int) int {.
// return value * value.
// }).
// // squared: [1, 4, 9, 16, 25].
func (slice *Slice[T]) Map(fn func(i int, value T) T) *Slice[T] {
s := make(Slice[T], slice.Length())
slice.Each(func(i int, value T) {
s.Replace(i, fn(i, value))
})
return &s
}
// MapReverse applies the provided function to each element in the slice in reverse order and creates a new slice containing the modified elements.
// It returns a new Slice[T] containing the transformed elements. The original slice is not modified.
//
// Example:.
//
// numbers := slice.Slice[int]{1, 2, 3, 4, 5}.
// reversedSquared := numbers.MapReverse(func(i int, value int) int {.
// return value * value.
// }).
// // reversedSquared: [25, 16, 9, 4, 1].
func (slice *Slice[T]) MapReverse(fn func(i int, value T) T) *Slice[T] {
s := &Slice[T]{}
slice.EachReverse(func(i int, value T) {
s.Append(fn(i, value))
})
return s
}
// Modify applies the provided function to each element in the slice and modifies the elements in place.
// It iterates over the slice, applying the function to each element along with its index, and replaces the element with the result.
//
// Example:.
//
// numbers := slice.Slice[int]{1, 2, 3, 4, 5}.
// modifiedSlice := numbers.Modify(func(i int, value int) int {.
// return value * 2.
// }).
// // modifiedSlice: [2, 4, 6, 8, 10].
func (slice *Slice[T]) Modify(fn func(i int, value T) T) *Slice[T] {
slice.Each(func(i int, value T) {
slice.Replace(i, fn(i, value))
})
return slice
}
// Poll removes the first element from the Slice and returns that removed element.
// It removes and returns the first element of the Slice if the Slice is not empty.
//
// Example:.
//
// s := &slice.Slice[int]{10, 20, 30}.
// value := s.Poll() // value will be 10, and s will be [20, 30].
func (slice *Slice[T]) Poll() T {
var v T
if !slice.IsEmpty() {
v = (*slice)[0]
*slice = (*slice)[1:]
}
return v
}
// PollLength removes the first element from the Slice and returns the removed element and the length of the modified Slice.
// It removes and returns the first element of the Slice along with the new length of the modified Slice if the Slice is not empty.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// value, length := s.PollLength() // value will be 1, and length will be 2.
func (slice *Slice[T]) PollLength() (T, int) {
return slice.Poll(), slice.Length()
}
// PollOK removes and returns the first element from the Slice if it is not empty.
// It checks whether the Slice is populated (not empty) and removes the first element.
// If the Slice is populated, it returns the removed element along with true; otherwise, it returns the zero value for the element and false.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// value, ok := s.PollOK().
// // 'value' will be 1, and 'ok' will be true as the Slice is not empty.
func (slice *Slice[T]) PollOK() (T, bool) {
var (
ok = slice.IsPopulated()
v T
)
if ok {
v = slice.Poll()
}
return v, ok
}
// Pop removes and returns the last element from the Slice if it is not empty.
// It checks whether the Slice is populated (not empty) and removes the last element.
// If the Slice is populated, it returns the removed element; otherwise, it returns the zero value for the element.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// value := s.Pop().
// // 'value' will be 3, and the Slice will become [1, 2].
func (slice *Slice[T]) Pop() T {
var v T
if slice.IsPopulated() {
l := slice.Length()
v = (*slice)[l-1]
*slice = (*slice)[:l-1]
}
return v
}
// PopLength removes the last element from the Slice and returns the removed element along with the length of the modified Slice.
// It removes and returns the last element of the Slice if the Slice is not empty, along with the new length of the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{10, 20, 30}.
// value, length := s.PopLength() // value will be 30, length will be 2, and s will be [10, 20].
func (slice *Slice[T]) PopLength() (T, int) {
return slice.Pop(), slice.Length()
}
// PopOK removes the last element from the Slice and returns a boolean indicating the outcome of the transaction.
// It removes the last element from the Slice and returns true if the Slice is not empty; otherwise, it returns false.
//
// Example:.
//
// s := &slice.Slice[int]{10, 20, 30}.
// value, ok := s.PopOK() // value will be 30, ok will be true, and s will be [10, 20].
func (slice *Slice[T]) PopOK() (T, bool) {
var (
ok = slice.IsPopulated()
v T
)
if ok {
v = slice.Pop()
}
return v, ok
}
// Precatenate merges the elements from the argument Slice to the head of the receiver Slice and returns the modified Slice.
// If the provided Slice (s) is not nil, it prepends its elements to the receiver Slice and returns a pointer to the modified Slice.
//
// Example:.
//
// s1 := &slice.Slice[int]{1, 2, 3}.
// s2 := &slice.Slice[int]{4, 5}.
// s1.Precatenate(s2) // s1 will be [4, 5, 1, 2, 3].
func (slice *Slice[T]) Precatenate(s *Slice[T]) *Slice[T] {
if s != nil {
slice.Prepend((*s)...)
}
return slice
}
// PrecatenateFunc prepends elements from another Slice to the head of the receiver Slice based on a provided predicate function.
// It iterates over each element in the source slice, invoking the provided function. If the function returns 'true' for an element,.
// that element is prepended to the receiver slice. If it returns 'false', the element is skipped.
//
// Example:.
//
// s1 := &slice.Slice[int]{1, 2, 3}.
// s2 := &slice.Slice[int]{4, 5, 6}.
// result := s1.PrecatenateFunc(s2, func(i int, value int) bool {.
// return value%2 == 0.
// }) // s1 will be modified to [4, 6, 2, 1, 3], and 'result' will be a pointer to 's1'.
func (slice *Slice[T]) PrecatenateFunc(s *Slice[T], fn func(i int, value T) bool) *Slice[T] {
return slice.PrependFunc(fn, (*s)...)
}
// PrecatenateLength merges the elements from the argument Slice to the head of the receiver Slice and returns the length of the modified Slice.
// If the provided Slice (s) is not nil, it prepends its elements to the receiver Slice and returns the length of the modified Slice.
//
// Example:.
//
// s1 := &slice.Slice[int]{1, 2, 3}.
// s2 := &slice.Slice[int]{4, 5}.
// length := s1.PrecatenateLength(s2) // length will be 5, and s1 will be [4, 5, 1, 2, 3].
func (slice *Slice[T]) PrecatenateLength(s *Slice[T]) int {
return slice.Precatenate(s).Length()
}
// Prepend adds one element to the head of the Slice and returns the modified Slice.
// It adds the specified values to the beginning of the existing Slice and returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{2, 3}.
// s.Prepend(1) // s will be [1, 2, 3].
func (slice *Slice[T]) Prepend(values ...T) *Slice[T] {
*slice = append(values, *slice...)
return slice
}
// PrependFunc prepends elements to the head of the receiver Slice based on a provided predicate function.
// It iterates over each element in the 'values' argument, invoking the provided function. If the function returns 'true' for an element,.
// that element is prepended to the receiver slice. If it returns 'false', the element is skipped.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// result := s.PrependFunc(func(i int, value int) bool {.
// return value%2 == 0.
// }, 4, 5, 6) // 's' will be modified to [6, 4, 2, 1, 3], and 'result' will be a pointer to 's'.
func (slice *Slice[T]) PrependFunc(fn func(i int, value T) bool, values ...T) *Slice[T] {
s := &Slice[T]{}
for i, value := range values {
if fn(i, value) {
s.Append(value)
}
}
*slice = *s.Concatenate(slice)
return slice
}
// PrependLength adds n elements to the head of the Slice and returns the length of the modified Slice.
// It adds the specified values to the beginning of the existing Slice and returns the length of the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{2, 3}.
// length := s.PrependLength(1, 0) // length will be 4, and s will be [1, 0, 2, 3].
func (slice *Slice[T]) PrependLength(values ...T) int {
return slice.Prepend(values...).Length()
}
// Reduce applies the provided function to each element in the slice and reduces the elements to a single value.
// It iterates over the slice, applying the function to each element along with its index and the current result value,.
// and accumulates the result. The result of the previous function call is passed as the third argument to the next function call.
// It returns the final reduced value.
//
// Example:.
//
// numbers := slice.Slice[int]({1, 2, 3, 4, 5}).
// sum := numbers.Reduce(func(i int, currentValue int, resultValue int) int {.
// return resultValue + currentValue.
// }).
// // sum: 15 (1 + 2 + 3 + 4 + 5).
func (slice *Slice[T]) Reduce(fn func(i int, currentValue T, resultValue T) T) T {
var resultValue T
slice.Each(func(i int, currentValue T) {
resultValue = fn(i, currentValue, resultValue)
})
return resultValue
}
// ReduceReverse iterates over the slice in reverse order and reduces the elements into a single value using the provided function.
// It starts from the last element and accumulates the result by applying the function to each element along with its index and the current accumulated result.
// The result of each iteration becomes the input for the next iteration.
//
// Example:.
//
// numbers := slice.Slice[int]{1, 2, 3, 4, 5}.
// sum := numbers.ReduceReverse(func(i int, currentValue, resultValue int) int {.
// return currentValue + resultValue.
// }).
// // sum: 15 (sum of all elements in the slice).
func (slice *Slice[T]) ReduceReverse(fn func(i int, currentValue T, resultValue T) T) T {
var resultValue T
slice.EachReverse(func(i int, currentValue T) {
resultValue = fn(i, currentValue, resultValue)
})
return resultValue
}
// Replace changes the contents of the Slice at the argument index if it is in bounds.
// It replaces the element at the specified index with the provided value if the index is within bounds and returns true.
// Otherwise, it returns false.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// ok := s.Replace(1, 4) // ok will be true, and s will be [1, 4, 3].
func (slice *Slice[T]) Replace(i int, value T) bool {
ok := slice.Bounds(i)
if ok {
(*slice)[i] = value
}
return ok
}
// Reverse reverses the Slice in linear time and returns the modified Slice.
// It reverses the order of elements in the Slice and returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// s.Reverse() // s will be [3, 2, 1].
func (slice *Slice[T]) Reverse() *Slice[T] {
var (
i = 0
j = slice.Length() - 1
)
for i < j {
slice.Swap(i, j)
i = i + 1
j = j - 1
}
return slice
}
// Set returns a unique slice, removing duplicate elements that have the same hash value.
// Returns the modified Slice at the end of the iteration.
// It removes duplicate elements from the slice, keeping only the first occurrence of each unique element.
// Returns a pointer to the modified Slice with unique elements.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 2, 3, 3, 3}.
// s.Set() // s will be [1, 2, 3].
func (slice *Slice[T]) Set() *Slice[T] {
var (
k string
m = map[string]bool{}
ok bool
s = &Slice[T]{}
)
slice.Each(func(_ int, value T) {
k = fmt.Sprintf("%v", value) // TODO: Check if there is a better way to generate key.
_, ok = m[k]
if !ok {
s.Append(value)
}
m[k] = true
})
*slice = *s
return slice
}
// Shuffle randomly shuffles the elements of the Slice and returns the modified Slice.
// It shuffles the elements of the Slice in a random order and returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// s.Shuffle() // s will be a random permutation of [1, 2, 3, 4, 5].
func (slice *Slice[T]) Shuffle() *Slice[T] {
rand.Shuffle(slice.Length(), func(i, j int) {
slice.Swap(i, j)
})
return slice
}
// Slice slices the Slice from i to j and returns a new Slice.
// It slices the Slice from the specified start (i) index to the end (j) index (inclusive),.
// and returns a pointer to the new Slice.
//
// Example:.
//
// numbers := slice.Slice[int]{1, 2, 3, 4, 5}.
// // Create a new slice containing elements at indexes 1 to 3 from the original slice.
// subset := numbers.Slice(1, 4).
// // Resulting subset: [2, 3, 4].
func (slice *Slice[T]) Slice(i int, j int) *Slice[T] {
if j < i {
i, j = j, i
}
s := (*slice)[i : j+1] // Include the element at index j.
return &s
}
// SortFunc sorts the elements of the slice based on a custom comparison function.
// Takes a comparison function that takes two indices (i, j) and two elements (a, b) of type T and returns true if element a should come before element b in the sorted order. If fn returns true, it means a is considered less than b in the sorting order.
//
// s := &slice.Slice[int]{5, 2, 8, 1, 9}.
// s.SortFunc(func(i, j int, a, b int) bool {.
// return a < b.
// }).
func (slice *Slice[T]) SortFunc(fn func(i int, j int, a T, b T) bool) *Slice[T] {
v := *slice // Copy the slice to a new variable.
sort.Slice(v, func(i int, j int) bool {
return fn(i, j, v[i], v[j]) // Use the copied slice (v) instead of slice.
})
*slice = v // Update the original slice with the sorted copy.
return slice
}
// Splice slices the Slice from i to j and returns the modified Slice.
// It slices the Slice from the specified start (i) index to the end (j) index (inclusive),.
// and returns a pointer to the modified Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3, 4, 5}.
// s.Splice(1, 3) // s will be [2, 3, 4].
func (slice *Slice[T]) Splice(i int, j int) *Slice[T] {
if j < i {
i, j = j, i
}
if slice.Bounds(i) && slice.Bounds(j) {
*slice = (*slice)[i : j+1] // Include the element at index j.
}
return slice
}
// Swap moves element i to j and j to i.
// If both indices (i and j) are within bounds, it swaps the elements at those positions in the Slice.
//
// Example:.
//
// s := &slice.Slice[int]{1, 2, 3}.
// s.Swap(0, 2) // s will be [3, 2, 1].
func (slice *Slice[T]) Swap(i int, j int) {
if slice.Bounds(i) && slice.Bounds(j) {
(*slice)[i], (*slice)[j] = (*slice)[j], (*slice)[i]
}
}
// New creates a new instance of the Slice[T] type and initializes it with the provided values.
// It allows you to create a new Slice and populate it with the specified elements.
//
// Example:.
//
// s := New[int](1, 2, 3, 4, 5).
// // 's' will be a pointer to a new Slice containing [1, 2, 3, 4, 5].
func New[T any](values ...T) *Slice[T] {
return (&Slice[T]{}).Append(values...)
}