-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice_iter.go
1195 lines (1081 loc) · 30.5 KB
/
slice_iter.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 g
import (
"context"
"iter"
"reflect"
"github.com/enetx/g/cmp"
"github.com/enetx/g/f"
)
// Pull converts the “push-style” iterator sequence seq
// into a “pull-style” iterator accessed by the two functions
// next and stop.
//
// Next returns the next value in the sequence
// and a boolean indicating whether the value is valid.
// When the sequence is over, next returns the zero V and false.
// It is valid to call next after reaching the end of the sequence
// or after calling stop. These calls will continue
// to return the zero V and false.
//
// Stop ends the iteration. It must be called when the caller is
// no longer interested in next values and next has not yet
// signaled that the sequence is over (with a false boolean return).
// It is valid to call stop multiple times and when next has
// already returned false.
//
// It is an error to call next or stop from multiple goroutines
// simultaneously.
func (seq SeqSlice[V]) Pull() (func() (V, bool), func()) { return iter.Pull(iter.Seq[V](seq)) }
// All checks whether all elements in the iterator satisfy the provided condition.
// This function is useful when you want to determine if all elements in an iterator
// meet a specific criteria.
//
// Parameters:
// - fn func(T) bool: A function that returns a boolean indicating whether the element satisfies
// the condition.
//
// Returns:
// - bool: True if all elements in the iterator satisfy the condition, false otherwise.
//
// Example usage:
//
// slice := g.SliceOf(1, 2, 3, 4, 5, 6, 7, -1, -2)
// isPositive := func(num int) bool { return num > 0 }
// allPositive := slice.Iter().All(isPositive)
//
// The resulting allPositive will be true if all elements returned by the iterator are positive.
func (seq SeqSlice[V]) All(fn func(v V) bool) bool {
for v := range seq {
if !fn(v) {
return false
}
}
return true
}
// Any checks whether any element in the iterator satisfies the provided condition.
// This function is useful when you want to determine if at least one element in an iterator
// meets a specific criteria.
//
// Parameters:
// - fn func(T) bool: A function that returns a boolean indicating whether the element satisfies
// the condition.
//
// Returns:
// - bool: True if at least one element in the iterator satisfies the condition, false otherwise.
//
// Example usage:
//
// slice := g.Slice[int]{1, 3, 5, 7, 9}
// isEven := func(num int) bool { return num%2 == 0 }
// anyEven := slice.Iter().Any(isEven)
//
// The resulting anyEven will be true if at least one element returned by the iterator is even.
func (seq SeqSlice[V]) Any(fn func(V) bool) bool {
for v := range seq {
if fn(v) {
return true
}
}
return false
}
// Chain concatenates the current iterator with other iterators, returning a new iterator.
//
// The function creates a new iterator that combines the elements of the current iterator
// with elements from the provided iterators in the order they are given.
//
// Params:
//
// - seqs ([]SeqSlice[V]): Other iterators to be concatenated with the current iterator.
//
// Returns:
//
// - sequence[V]: A new iterator containing elements from the current iterator and the provided iterators.
//
// Example usage:
//
// iter1 := g.Slice[int]{1, 2, 3}.Iter()
// iter2 := g.Slice[int]{4, 5, 6}.Iter()
// iter1.Chain(iter2).Collect().Print()
//
// Output: [1, 2, 3, 4, 5, 6]
//
// The resulting iterator will contain elements from both iterators in the specified order.
func (seq SeqSlice[V]) Chain(seqs ...SeqSlice[V]) SeqSlice[V] {
return chainSlice(append([]SeqSlice[V]{seq}, seqs...)...)
}
// Chunks returns an iterator that yields chunks of elements of the specified size.
//
// The function creates a new iterator that yields chunks of elements from the original iterator,
// with each chunk containing elements of the specified size.
//
// Params:
//
// - n (Int): The size of each chunk.
//
// Returns:
//
// - SeqSlices[V]: An iterator yielding chunks of elements of the specified size.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
// chunks := slice.Iter().Chunks(2).Collect()
//
// Output: [Slice[1, 2] Slice[3, 4] Slice[5, 6]]
//
// The resulting iterator will yield chunks of elements, each containing the specified number of elements.
func (seq SeqSlice[V]) Chunks(n Int) SeqSlices[V] { return chunks(seq, n.Std()) }
// Collect gathers all elements from the iterator into a Slice.
func (seq SeqSlice[V]) Collect() Slice[V] {
collection := make([]V, 0)
seq(func(v V) bool {
collection = append(collection, v)
return true
})
return collection
}
// Collect gathers all elements from the iterator into a []Slice.
func (seqs SeqSlices[V]) Collect() []Slice[V] {
collection := make([]Slice[V], 0)
seqs(func(v []V) bool {
inner := ToSeqSlice(v).Collect()
collection = append(collection, inner)
return true
})
return collection
}
// Count consumes the iterator, counting the number of iterations and returning it.
func (seq SeqSlice[V]) Count() Int { return countSlice(seq) }
// Counter returns a SeqMapOrd[V, uint] with the counts of each unique element in the slice.
// This function is useful when you want to count the occurrences of each unique element in a slice.
//
// Returns:
//
// - SeqMapOrd[V, uint]: with keys representing the unique elements in the slice
// and values representing the counts of those elements.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3, 1, 2, 1}
// counts := slice.Iter().Counter().Collect()
// // The counts ordered Map will contain:
// // 1 -> 3 (since 1 appears three times)
// // 2 -> 2 (since 2 appears two times)
// // 3 -> 1 (since 3 appears once)
func (seq SeqSlice[V]) Counter() SeqMapOrd[V, Int] { return counterSlice(seq) }
// Combinations generates all combinations of length 'n' from the sequence.
func (seq SeqSlice[V]) Combinations(n Int) SeqSlices[V] { return combinations(seq, n.Std()) }
// Cycle returns an iterator that endlessly repeats the elements of the current sequence.
func (seq SeqSlice[V]) Cycle() SeqSlice[V] { return cycleSlice(seq) }
// Exclude returns a new iterator excluding elements that satisfy the provided function.
//
// The function applies the provided function to each element of the iterator.
// If the function returns true for an element, that element is excluded from the resulting iterator.
//
// Parameters:
//
// - fn (func(T) bool): The function to be applied to each element of the iterator
// to determine if it should be excluded from the result.
//
// Returns:
//
// - seqSlice[V]: A new iterator containing the elements that do not satisfy the given condition.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3, 4, 5}
// notEven := slice.Iter().
// Exclude(
// func(val int) bool {
// return val%2 == 0
// }).
// Collect()
// notEven.Print()
//
// Output: [1, 3, 5]
//
// The resulting iterator will contain only the elements that do not satisfy the provided function.
func (seq SeqSlice[V]) Exclude(fn func(V) bool) SeqSlice[V] { return excludeSlice(seq, fn) }
// Enumerate adds an index to each element in the iterator.
//
// Returns:
//
// - SeqMapOrd[Int, V] An iterator with each element of type Pair[Int, V], where the first
// element of the pair is the index and the second element is the original element from the
// iterator.
//
// Example usage:
//
// ps := g.SliceOf[g.String]("bbb", "ddd", "xxx", "aaa", "ccc").
// Iter().
// Enumerate().
// Collect()
//
// ps.Print()
//
// Output: MapOrd{0:bbb, 1:ddd, 2:xxx, 3:aaa, 4:ccc}
func (seq SeqSlice[V]) Enumerate() SeqMapOrd[Int, V] { return enumerate(seq) }
// Dedup creates a new iterator that removes consecutive duplicate elements from the original iterator,
// leaving only one occurrence of each unique element. If the iterator is sorted, all elements will be unique.
//
// Parameters:
// - None
//
// Returns:
// - SeqSlice[V]: A new iterator with consecutive duplicates removed.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 2, 3, 4, 4, 4, 5}
// iter := slice.Iter().Dedup()
// result := iter.Collect()
// result.Print()
//
// Output: [1 2 3 4 5]
//
// The resulting iterator will contain only unique elements, removing consecutive duplicates.
func (seq SeqSlice[V]) Dedup() SeqSlice[V] { return dedupSlice(seq) }
// Filter returns a new iterator containing only the elements that satisfy the provided function.
//
// The function applies the provided function to each element of the iterator.
// If the function returns true for an element, that element is included in the resulting iterator.
//
// Parameters:
//
// - fn (func(T) bool): The function to be applied to each element of the iterator
// to determine if it should be included in the result.
//
// Returns:
//
// - SeqSlice[V]: A new iterator containing the elements that satisfy the given condition.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3, 4, 5}
// even := slice.Iter().
// Filter(
// func(val int) bool {
// return val%2 == 0
// }).
// Collect()
// even.Print()
//
// Output: [2 4].
//
// The resulting iterator will contain only the elements that satisfy the provided function.
func (seq SeqSlice[V]) Filter(fn func(V) bool) SeqSlice[V] { return filterSlice(seq, fn) }
// Fold accumulates values in the iterator using a function.
//
// The function iterates through the elements of the iterator, accumulating values
// using the provided function and an initial value.
//
// Params:
//
// - init (V): The initial value for accumulation.
// - fn (func(V, V) V): The function that accumulates values; it takes two arguments
// of type V and returns a value of type T.
//
// Returns:
//
// - T: The accumulated value after applying the function to all elements.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3, 4, 5}
// sum := slice.Iter().
// Fold(0,
// func(acc, val int) int {
// return acc + val
// })
// fmt.Println(sum)
//
// Output: 15.
//
// The resulting value will be the accumulation of elements based on the provided function.
func (seq SeqSlice[V]) Fold(init V, fn func(acc, val V) V) V { return fold(seq, init, fn) }
// ForEach iterates through all elements and applies the given function to each.
//
// The function applies the provided function to each element of the iterator.
//
// Params:
//
// - fn (func(T)): The function to apply to each element.
//
// Example usage:
//
// iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
// iter.ForEach(func(val T) {
// fmt.Println(val) // Replace this with the function logic you need.
// })
//
// The provided function will be applied to each element in the iterator.
func (seq SeqSlice[V]) ForEach(fn func(v V)) {
seq(func(v V) bool {
fn(v)
return true
})
}
// Flatten flattens an iterator of iterators into a single iterator.
//
// The function creates a new iterator that flattens a sequence of iterators,
// returning a single iterator containing elements from each iterator in sequence.
//
// Returns:
//
// - SeqSlice[V]: A single iterator containing elements from the sequence of iterators.
//
// Example usage:
//
// nestedSlice := g.Slice[any]{
// 1,
// g.SliceOf(2, 3),
// "abc",
// g.SliceOf("def", "ghi"),
// g.SliceOf(4.5, 6.7),
// }
//
// nestedSlice.Iter().Flatten().Collect().Print()
//
// Output: Slice[1, 2, 3, abc, def, ghi, 4.5, 6.7]
//
// The resulting iterator will contain elements from each iterator in sequence.
func (seq SeqSlice[V]) Flatten() SeqSlice[V] { return flatten(seq) }
// Inspect creates a new iterator that wraps around the current iterator
// and allows inspecting each element as it passes through.
func (seq SeqSlice[V]) Inspect(fn func(v V)) SeqSlice[V] { return inspectSlice(seq, fn) }
// Map transforms each element in the iterator using the given function.
//
// The function creates a new iterator by applying the provided function to each element
// of the original iterator.
//
// Params:
//
// - fn (func(T) T): The function used to transform elements.
//
// Returns:
//
// - SeqSlice[V]: A iterator containing elements transformed by the provided function.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3}
// doubled := slice.
// Iter().
// Map(
// func(val int) int {
// return val * 2
// }).
// Collect()
// doubled.Print()
//
// Output: [2 4 6].
//
// The resulting iterator will contain elements transformed by the provided function.
func (seq SeqSlice[V]) Map(transform func(V) V) SeqSlice[V] { return sliceMap(seq, transform) }
// Partition divides the elements of the iterator into two separate slices based on a given predicate function.
//
// The function takes a predicate function 'fn', which should return true or false for each element in the iterator.
// Elements for which 'fn' returns true are collected into the left slice, while those for which 'fn' returns false
// are collected into the right slice.
//
// Params:
//
// - fn (func(V) bool): The predicate function used to determine the placement of elements.
//
// Returns:
//
// - (Slice[V], Slice[V]): Two slices representing elements that satisfy and don't satisfy the predicate, respectively.
//
// Example usage:
//
// evens, odds := g.Slice[int]{1, 2, 3, 4, 5}.
// Iter().
// Partition(
// func(v int) bool {
// return v%2 == 0
// })
//
// fmt.Println("Even numbers:", evens) // Output: Even numbers: Slice[2, 4]
// fmt.Println("Odd numbers:", odds) // Output: Odd numbers: Slice[1, 3, 5]
//
// The resulting two slices will contain elements separated based on whether they satisfy the predicate or not.
func (seq SeqSlice[V]) Partition(fn func(v V) bool) (Slice[V], Slice[V]) { return partition(seq, fn) }
// Permutations generates iterators of all permutations of elements.
//
// The function uses a recursive approach to generate all the permutations of the elements.
// If the iterator is empty or contains a single element, it returns the iterator itself
// wrapped in a single-element iterator.
//
// Returns:
//
// - seqSlices[V]: An iterator of iterators containing all possible permutations of the
// elements in the iterator.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3}
// perms := slice.Iter().Permutations().Collect()
// for _, perm := range perms {
// fmt.Println(perm)
// }
//
// Output:
//
// Slice[1, 2, 3]
// Slice[1, 3, 2]
// Slice[2, 1, 3]
// Slice[2, 3, 1]
// Slice[3, 1, 2]
// Slice[3, 2, 1]
//
// The resulting iterator will contain iterators representing all possible permutations
// of the elements in the original iterator.
func (seq SeqSlice[V]) Permutations() SeqSlices[V] { return permutations(seq) }
// Range iterates through elements until the given function returns false.
//
// The function iterates through the elements of the iterator and applies the provided function
// to each element. It stops iteration when the function returns false for an element.
//
// Params:
//
// - fn (func(T) bool): The function that evaluates elements for continuation of iteration.
//
// Example usage:
//
// iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
// iter.Range(func(val int) bool {
// fmt.Println(val) // Replace this with the function logic you need.
// return val < 5 // Replace this with the condition for continuing iteration.
// })
//
// The iteration will stop when the provided function returns false for an element.
func (seq SeqSlice[V]) Range(fn func(v V) bool) {
seq(func(v V) bool {
return fn(v)
})
}
// Skip returns a new iterator skipping the first n elements.
//
// The function creates a new iterator that skips the first n elements of the current iterator
// and returns an iterator starting from the (n+1)th element.
//
// Params:
//
// - n (uint): The number of elements to skip from the beginning of the iterator.
//
// Returns:
//
// - SeqSlice[V]: An iterator that starts after skipping the first n elements.
//
// Example usage:
//
// iter := g.Slice[int]{1, 2, 3, 4, 5, 6}.Iter()
// iter.Skip(3).Collect().Print()
//
// Output: [4, 5, 6]
//
// The resulting iterator will start after skipping the specified number of elements.
func (seq SeqSlice[V]) Skip(n uint) SeqSlice[V] { return skipSlice(seq, n) }
// StepBy creates a new iterator that iterates over every N-th element of the original iterator.
// This function is useful when you want to skip a specific number of elements between each iteration.
//
// Parameters:
// - n uint: The step size, indicating how many elements to skip between each iteration.
//
// Returns:
// - SeqSlice[V]: A new iterator that produces elements from the original iterator with a step size of N.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
// iter := slice.Iter().StepBy(3)
// result := iter.Collect()
// result.Print()
//
// Output: [1 4 7 10]
//
// The resulting iterator will produce elements from the original iterator with a step size of N.
func (seq SeqSlice[V]) StepBy(n uint) SeqSlice[V] { return stepbySlice(seq, n) }
// Sort returns a new iterator containing the elements from the current iterator
// in sorted order. The elements must be of a comparable type.
//
// Example:
//
// g.SliceOf(9, 8, 9, 8, 0, 1, 1, 1, 2, 7, 2, 2, 2, 3, 4, 5).
// Iter().
// Sort().
// Collect().
// Print()
//
// Output: Slice[0, 1, 1, 1, 2, 2, 2, 2, 3, 4, 5, 7, 8, 8, 9, 9]
//
// The returned iterator is of type sequence[V], which implements the iterator
// interface for further iteration over the sorted elements.
// func (seq SeqSlice[V]) Sort() SeqSlice[V] { return sortiSlice(seq) }
// SortBy applies a custom sorting function to the elements in the iterator
// and returns a new iterator containing the sorted elements.
//
// The sorting function 'fn' should take two arguments, 'a' and 'b' of type T,
// and return true if 'a' should be ordered before 'b', and false otherwise.
//
// Example:
//
// g.SliceOf("a", "c", "b").
// Iter().
// SortBy(func(a, b string) bool { return a > b }).
// Collect().
// Print()
//
// Output: Slice[c, b, a]
//
// The returned iterator is of type sequence[V], which implements the iterator
// interface for further iteration over the sorted elements.
func (seq SeqSlice[V]) SortBy(fn func(a, b V) cmp.Ordered) SeqSlice[V] { return sortbySlice(seq, fn) }
// Take returns a new iterator with the first n elements.
// The function creates a new iterator containing the first n elements from the original iterator.
func (seq SeqSlice[V]) Take(n uint) SeqSlice[V] { return takeSlice(seq, n) }
// ToChan converts the iterator into a channel, optionally with context(s).
//
// The function converts the elements of the iterator into a channel for streaming purposes.
// Optionally, it accepts context(s) to handle cancellation or timeout scenarios.
//
// Params:
//
// - ctxs (context.Context): Optional context(s) to control the channel behavior (e.g., cancellation).
//
// Returns:
//
// - chan V: A channel containing the elements from the iterator.
//
// Example usage:
//
// iter := g.Slice[int]{1, 2, 3}.Iter()
// ctx, cancel := context.WithCancel(context.Background())
// defer cancel() // Ensure cancellation to avoid goroutine leaks.
// ch := iter.ToChan(ctx)
// for val := range ch {
// fmt.Println(val)
// }
//
// The resulting channel allows streaming elements from the iterator with optional context handling.
func (seq SeqSlice[V]) ToChan(ctxs ...context.Context) chan V {
ch := make(chan V)
ctx := context.Background()
if len(ctxs) != 0 {
ctx = ctxs[0]
}
go func() {
defer close(ch)
for v := range seq {
select {
case <-ctx.Done():
return
default:
ch <- v
}
}
}()
return ch
}
// Unique returns an iterator with only unique elements.
//
// The function returns an iterator containing only the unique elements from the original iterator.
//
// Returns:
//
// - SeqSlice[V]: An iterator containing unique elements from the original iterator.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3, 2, 4, 5, 3}
// unique := slice.Iter().Unique().Collect()
// unique.Print()
//
// Output: [1, 2, 3, 4, 5].
//
// The resulting iterator will contain only unique elements from the original iterator.
func (seq SeqSlice[V]) Unique() SeqSlice[V] { return uniqueSlice(seq) }
// Zip combines elements from the current sequence and another sequence into pairs,
// creating an ordered map with identical keys and values of type V.
func (seq SeqSlice[V]) Zip(two SeqSlice[V]) SeqMapOrd[V, V] { return zip(seq, two) }
// Find searches for an element in the iterator that satisfies the provided function.
//
// The function iterates through the elements of the iterator and returns the first element
// for which the provided function returns true.
//
// Params:
//
// - fn (func(T) bool): The function used to test elements for a condition.
//
// Returns:
//
// - Option[V]: An Option containing the first element that satisfies the condition; None if not found.
//
// Example usage:
//
// iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
//
// found := iter.Find(
// func(i int) bool {
// return i == 2
// })
//
// if found.IsSome() {
// fmt.Println("Found:", found.Some())
// } else {
// fmt.Println("Not found.")
// }
//
// The resulting Option may contain the first element that satisfies the condition, or None if not found.
func (seq SeqSlice[V]) Find(fn func(v V) bool) Option[V] { return findSlice(seq, fn) }
// Windows returns an iterator that yields sliding windows of elements of the specified size.
//
// The function creates a new iterator that yields windows of elements from the original iterator,
// where each window is a slice containing elements of the specified size and moves one element at a time.
//
// Params:
//
// - size (int): The size of each window.
//
// Returns:
//
// - seqSlices[V]: An iterator yielding sliding windows of elements of the specified size.
//
// Example usage:
//
// slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
// windows := slice.Iter().Windows(3).Collect()
//
// Output: [Slice[1, 2, 3] Slice[2, 3, 4] Slice[3, 4, 5] Slice[4, 5, 6]]
//
// The resulting iterator will yield sliding windows of elements, each containing the specified number of elements.
func (seq SeqSlice[V]) Windows(n Int) SeqSlices[V] { return windows(seq, n.Std()) }
// FromChan converts a channel into an iterator.
//
// This function takes a channel as input and converts its elements into an iterator,
// allowing seamless integration of channels into iterator-based processing pipelines.
// It continuously reads from the channel until it's closed,
// yielding each element to the provided yield function.
//
// Parameters:
// - ch (<-chan V): The input channel to convert into an iterator.
//
// Returns:
// - SeqSlice[V]: An iterator that yields elements from the channel.
//
// Example usage:
//
// ch := make(chan int)
// go func() {
// defer close(ch)
// for i := 1; i <= 5; i++ {
// ch <- i
// }
// }()
//
// // Convert the channel into an iterator and apply filtering and mapping operations.
// g.FromChan(ch).
// Filter(func(i int) bool { return i%2 == 0 }). // Filter even numbers.
// Map(func(i int) int { return i * 2 }). // Double each element.
// Collect(). // Collect the results into a slice.
// Print() // Print the collected results.
//
// Output: Slice[4, 8]
//
// The resulting iterator will yield elements from the provided channel, filtering out odd numbers,
// doubling each even number, and finally collecting the results into a slice.
func FromChan[V any](ch <-chan V) SeqSlice[V] {
return func(yield func(V) bool) {
for v := range ch {
if !yield(v) {
return
}
}
}
}
func ToSeqSlice[V any](slice []V) SeqSlice[V] {
return func(yield func(V) bool) {
for _, v := range slice {
if !yield(v) {
return
}
}
}
}
func chainSlice[V any](seqs ...SeqSlice[V]) SeqSlice[V] {
return func(yield func(V) bool) {
for _, seq := range seqs {
seq(func(v V) bool {
return yield(v)
})
}
}
}
func sliceMap[V, U any](seq SeqSlice[V], fn func(V) U) SeqSlice[U] {
return func(yield func(U) bool) {
seq(func(v V) bool {
return yield(fn(v))
})
}
}
func filterSlice[V any](seq SeqSlice[V], fn func(V) bool) SeqSlice[V] {
return func(yield func(V) bool) {
seq(func(v V) bool {
if fn(v) {
return yield(v)
}
return true
})
}
}
func excludeSlice[V any](seq SeqSlice[V], fn func(V) bool) SeqSlice[V] {
return filterSlice(seq, func(v V) bool { return !fn(v) })
}
func cycleSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
return func(yield func(V) bool) {
var saved []V
seq(func(v V) bool {
saved = append(saved, v)
return yield(v)
})
for len(saved) > 0 {
for _, v := range saved {
if !yield(v) {
return
}
}
}
}
}
func stepbySlice[V any](seq SeqSlice[V], n uint) SeqSlice[V] {
return func(yield func(V) bool) {
i := uint(0)
seq(func(v V) bool {
i++
if (i-1)%n == 0 {
return yield(v)
}
return true
})
}
}
func takeSlice[V any](seq SeqSlice[V], n uint) SeqSlice[V] {
return func(yield func(V) bool) {
seq(func(v V) bool {
if n == 0 {
return false
}
n--
return yield(v)
})
}
}
func uniqueSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
return func(yield func(V) bool) {
seen := NewSet[any]()
seq(func(v V) bool {
if !seen.Contains(v) {
seen.Add(v)
return yield(v)
}
return true
})
}
}
// works slower
// func dedupSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
// var current V
// eq := f.Eqd[any]
// if f.Comparable(current) {
// eq = f.Eq
// }
// return func(yield func(V) bool) {
// seq(func(v V) bool {
// if eq(current)(v) {
// return true
// }
// current = v
// return yield(v)
// })
// }
// }
func dedupSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
var current V
comparable := f.Comparable(current)
return func(yield func(V) bool) {
seq(func(v V) bool {
if comparable {
if f.Eq[any](current)(v) {
return true
}
} else {
if f.Eqd(current)(v) {
return true
}
}
current = v
return yield(v)
})
}
}
// func sortiSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
// items := seq.Collect()
// items.Sort()
// return items.Iter()
// }
func sortbySlice[V any](seq SeqSlice[V], cmp func(a, b V) cmp.Ordered) SeqSlice[V] {
items := seq.Collect()
items.SortBy(cmp)
return items.Iter()
}
func skipSlice[V any](seq SeqSlice[V], n uint) SeqSlice[V] {
return func(yield func(V) bool) {
seq(func(v V) bool {
if n > 0 {
n--
return true
}
return yield(v)
})
}
}
func inspectSlice[V any](seq SeqSlice[V], fn func(V)) SeqSlice[V] {
return func(yield func(V) bool) {
seq(func(v V) bool {
fn(v)
return yield(v)
})
}
}
func enumerate[V any](seq SeqSlice[V]) SeqMapOrd[Int, V] {
return func(yield func(Int, V) bool) {
i := Int(-1)
seq(func(v V) bool {
i++
return yield(i, v)
})
}
}
func zip[V, U any](one SeqSlice[V], two SeqSlice[U]) SeqMapOrd[V, U] {
return func(yield func(V, U) bool) {
oneNext, oneStop := one.Pull()
defer oneStop()
twoNext, twoStop := two.Pull()
defer twoStop()
for {
one, ok := oneNext()
if !ok {
return
}
two, ok := twoNext()
if !ok {
return
}
if !yield(one, two) {
return
}
}
}
}
func fold[V any](seq SeqSlice[V], init V, fn func(V, V) V) V {
seq(func(v V) bool {
init = fn(init, v)
return true
})
return init
}
func findSlice[V any](seq SeqSlice[V], fn func(V) bool) (r Option[V]) {
seq(func(v V) bool {
if !fn(v) {
return true
}
r = Some(v)
return false
})
return r
}
func chunks[V any](seq SeqSlice[V], n int) SeqSlices[V] {
return func(yield func([]V) bool) {
buf := make([]V, 0, n)
seq(func(v V) bool {
if len(buf) == n {
clear(buf)
buf = buf[:0]
}
if len(buf) < n-1 {
buf = append(buf, v)
return true
}
if len(buf) < n {
buf = append(buf, v)
return yield(buf)
}
return yield(buf)
})
if len(buf) < n {