github.com/enetx/g@v1.0.80/slice_iter.go (about)

     1  package g
     2  
     3  import (
     4  	"context"
     5  	"iter"
     6  	"reflect"
     7  
     8  	"github.com/enetx/g/cmp"
     9  	"github.com/enetx/g/f"
    10  )
    11  
    12  // Pull converts the “push-style” iterator sequence seq
    13  // into a “pull-style” iterator accessed by the two functions
    14  // next and stop.
    15  //
    16  // Next returns the next value in the sequence
    17  // and a boolean indicating whether the value is valid.
    18  // When the sequence is over, next returns the zero V and false.
    19  // It is valid to call next after reaching the end of the sequence
    20  // or after calling stop. These calls will continue
    21  // to return the zero V and false.
    22  //
    23  // Stop ends the iteration. It must be called when the caller is
    24  // no longer interested in next values and next has not yet
    25  // signaled that the sequence is over (with a false boolean return).
    26  // It is valid to call stop multiple times and when next has
    27  // already returned false.
    28  //
    29  // It is an error to call next or stop from multiple goroutines
    30  // simultaneously.
    31  func (seq SeqSlice[V]) Pull() (func() (V, bool), func()) { return iter.Pull(iter.Seq[V](seq)) }
    32  
    33  // All checks whether all elements in the iterator satisfy the provided condition.
    34  // This function is useful when you want to determine if all elements in an iterator
    35  // meet a specific criteria.
    36  //
    37  // Parameters:
    38  // - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies
    39  // the condition.
    40  //
    41  // Returns:
    42  // - bool: True if all elements in the iterator satisfy the condition, false otherwise.
    43  //
    44  // Example usage:
    45  //
    46  //	slice := g.SliceOf(1, 2, 3, 4, 5, 6, 7, -1, -2)
    47  //	isPositive := func(num int) bool { return num > 0 }
    48  //	allPositive := slice.Iter().All(isPositive)
    49  //
    50  // The resulting allPositive will be true if all elements returned by the iterator are positive.
    51  func (seq SeqSlice[V]) All(fn func(v V) bool) bool {
    52  	for v := range seq {
    53  		if !fn(v) {
    54  			return false
    55  		}
    56  	}
    57  
    58  	return true
    59  }
    60  
    61  // Any checks whether any element in the iterator satisfies the provided condition.
    62  // This function is useful when you want to determine if at least one element in an iterator
    63  // meets a specific criteria.
    64  //
    65  // Parameters:
    66  // - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies
    67  // the condition.
    68  //
    69  // Returns:
    70  // - bool: True if at least one element in the iterator satisfies the condition, false otherwise.
    71  //
    72  // Example usage:
    73  //
    74  //	slice := g.Slice[int]{1, 3, 5, 7, 9}
    75  //	isEven := func(num int) bool { return num%2 == 0 }
    76  //	anyEven := slice.Iter().Any(isEven)
    77  //
    78  // The resulting anyEven will be true if at least one element returned by the iterator is even.
    79  func (seq SeqSlice[V]) Any(fn func(V) bool) bool {
    80  	for v := range seq {
    81  		if fn(v) {
    82  			return true
    83  		}
    84  	}
    85  
    86  	return false
    87  }
    88  
    89  // Chain concatenates the current iterator with other iterators, returning a new iterator.
    90  //
    91  // The function creates a new iterator that combines the elements of the current iterator
    92  // with elements from the provided iterators in the order they are given.
    93  //
    94  // Params:
    95  //
    96  // - seqs ([]SeqSlice[V]): Other iterators to be concatenated with the current iterator.
    97  //
    98  // Returns:
    99  //
   100  // - sequence[V]: A new iterator containing elements from the current iterator and the provided iterators.
   101  //
   102  // Example usage:
   103  //
   104  //	iter1 := g.Slice[int]{1, 2, 3}.Iter()
   105  //	iter2 := g.Slice[int]{4, 5, 6}.Iter()
   106  //	iter1.Chain(iter2).Collect().Print()
   107  //
   108  // Output: [1, 2, 3, 4, 5, 6]
   109  //
   110  // The resulting iterator will contain elements from both iterators in the specified order.
   111  func (seq SeqSlice[V]) Chain(seqs ...SeqSlice[V]) SeqSlice[V] {
   112  	return chainSlice(append([]SeqSlice[V]{seq}, seqs...)...)
   113  }
   114  
   115  // Chunks returns an iterator that yields chunks of elements of the specified size.
   116  //
   117  // The function creates a new iterator that yields chunks of elements from the original iterator,
   118  // with each chunk containing elements of the specified size.
   119  //
   120  // Params:
   121  //
   122  // - n (Int): The size of each chunk.
   123  //
   124  // Returns:
   125  //
   126  // - SeqSlices[V]: An iterator yielding chunks of elements of the specified size.
   127  //
   128  // Example usage:
   129  //
   130  //	slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
   131  //	chunks := slice.Iter().Chunks(2).Collect()
   132  //
   133  // Output: [Slice[1, 2] Slice[3, 4] Slice[5, 6]]
   134  //
   135  // The resulting iterator will yield chunks of elements, each containing the specified number of elements.
   136  func (seq SeqSlice[V]) Chunks(n Int) SeqSlices[V] { return chunks(seq, n.Std()) }
   137  
   138  // Collect gathers all elements from the iterator into a Slice.
   139  func (seq SeqSlice[V]) Collect() Slice[V] {
   140  	collection := make([]V, 0)
   141  
   142  	seq(func(v V) bool {
   143  		collection = append(collection, v)
   144  		return true
   145  	})
   146  
   147  	return collection
   148  }
   149  
   150  // Collect gathers all elements from the iterator into a []Slice.
   151  func (seqs SeqSlices[V]) Collect() []Slice[V] {
   152  	collection := make([]Slice[V], 0)
   153  
   154  	seqs(func(v []V) bool {
   155  		inner := ToSeqSlice(v).Collect()
   156  		collection = append(collection, inner)
   157  		return true
   158  	})
   159  
   160  	return collection
   161  }
   162  
   163  // Count consumes the iterator, counting the number of iterations and returning it.
   164  func (seq SeqSlice[V]) Count() Int { return countSlice(seq) }
   165  
   166  // Counter returns a SeqMapOrd[V, Int] with the counts of each unique element in the slice.
   167  // This function is useful when you want to count the occurrences of each unique element in a slice.
   168  //
   169  // Returns:
   170  //
   171  // - SeqMapOrd[V, Int]: with keys representing the unique elements in the slice
   172  // and values representing the counts of those elements.
   173  //
   174  // Example usage:
   175  //
   176  //	slice := g.Slice[int]{1, 2, 3, 1, 2, 1}
   177  //	counts := slice.Iter().Counter().Collect()
   178  //	// The counts ordered Map will contain:
   179  //	// 1 -> 3 (since 1 appears three times)
   180  //	// 2 -> 2 (since 2 appears two times)
   181  //	// 3 -> 1 (since 3 appears once)
   182  func (seq SeqSlice[V]) Counter() SeqMapOrd[V, Int] { return counterSlice(seq) }
   183  
   184  // Combinations generates all combinations of length 'n' from the sequence.
   185  func (seq SeqSlice[V]) Combinations(n Int) SeqSlices[V] { return combinations(seq, n.Std()) }
   186  
   187  // Cycle returns an iterator that endlessly repeats the elements of the current sequence.
   188  func (seq SeqSlice[V]) Cycle() SeqSlice[V] { return cycleSlice(seq) }
   189  
   190  // Exclude returns a new iterator excluding elements that satisfy the provided function.
   191  //
   192  // The function applies the provided function to each element of the iterator.
   193  // If the function returns true for an element, that element is excluded from the resulting iterator.
   194  //
   195  // Parameters:
   196  //
   197  // - fn (func(V) bool): The function to be applied to each element of the iterator
   198  // to determine if it should be excluded from the result.
   199  //
   200  // Returns:
   201  //
   202  // - SeqSlice[V]: A new iterator containing the elements that do not satisfy the given condition.
   203  //
   204  // Example usage:
   205  //
   206  //	slice := g.Slice[int]{1, 2, 3, 4, 5}
   207  //	notEven := slice.Iter().
   208  //		Exclude(
   209  //			func(val int) bool {
   210  //				return val%2 == 0
   211  //			}).
   212  //		Collect()
   213  //	notEven.Print()
   214  //
   215  // Output: [1, 3, 5]
   216  //
   217  // The resulting iterator will contain only the elements that do not satisfy the provided function.
   218  func (seq SeqSlice[V]) Exclude(fn func(V) bool) SeqSlice[V] { return excludeSlice(seq, fn) }
   219  
   220  // Enumerate adds an index to each element in the iterator.
   221  //
   222  // Returns:
   223  //
   224  // - SeqMapOrd[Int, V] An iterator with each element of type Pair[Int, V], where the first
   225  // element of the pair is the index and the second element is the original element from the
   226  // iterator.
   227  //
   228  // Example usage:
   229  //
   230  //	ps := g.SliceOf[g.String]("bbb", "ddd", "xxx", "aaa", "ccc").
   231  //		Iter().
   232  //		Enumerate().
   233  //		Collect()
   234  //
   235  //	ps.Print()
   236  //
   237  // Output: MapOrd{0:bbb, 1:ddd, 2:xxx, 3:aaa, 4:ccc}
   238  func (seq SeqSlice[V]) Enumerate() SeqMapOrd[Int, V] { return enumerate(seq) }
   239  
   240  // Dedup creates a new iterator that removes consecutive duplicate elements from the original iterator,
   241  // leaving only one occurrence of each unique element. If the iterator is sorted, all elements will be unique.
   242  //
   243  // Parameters:
   244  // - None
   245  //
   246  // Returns:
   247  // - SeqSlice[V]: A new iterator with consecutive duplicates removed.
   248  //
   249  // Example usage:
   250  //
   251  //	slice := g.Slice[int]{1, 2, 2, 3, 4, 4, 4, 5}
   252  //	iter := slice.Iter().Dedup()
   253  //	result := iter.Collect()
   254  //	result.Print()
   255  //
   256  // Output: [1 2 3 4 5]
   257  //
   258  // The resulting iterator will contain only unique elements, removing consecutive duplicates.
   259  func (seq SeqSlice[V]) Dedup() SeqSlice[V] { return dedupSlice(seq) }
   260  
   261  // Filter returns a new iterator containing only the elements that satisfy the provided function.
   262  //
   263  // The function applies the provided function to each element of the iterator.
   264  // If the function returns true for an element, that element is included in the resulting iterator.
   265  //
   266  // Parameters:
   267  //
   268  // - fn (func(V) bool): The function to be applied to each element of the iterator
   269  // to determine if it should be included in the result.
   270  //
   271  // Returns:
   272  //
   273  // - SeqSlice[V]: A new iterator containing the elements that satisfy the given condition.
   274  //
   275  // Example usage:
   276  //
   277  //	slice := g.Slice[int]{1, 2, 3, 4, 5}
   278  //	even := slice.Iter().
   279  //		Filter(
   280  //			func(val int) bool {
   281  //				return val%2 == 0
   282  //			}).
   283  //		Collect()
   284  //	even.Print()
   285  //
   286  // Output: [2 4].
   287  //
   288  // The resulting iterator will contain only the elements that satisfy the provided function.
   289  func (seq SeqSlice[V]) Filter(fn func(V) bool) SeqSlice[V] { return filterSlice(seq, fn) }
   290  
   291  // Fold accumulates values in the iterator using a function.
   292  //
   293  // The function iterates through the elements of the iterator, accumulating values
   294  // using the provided function and an initial value.
   295  //
   296  // Params:
   297  //
   298  //   - init (V): The initial value for accumulation.
   299  //   - fn (func(V, V) V): The function that accumulates values; it takes two arguments
   300  //     of type V and returns a value of type V.
   301  //
   302  // Returns:
   303  //
   304  // - T: The accumulated value after applying the function to all elements.
   305  //
   306  // Example usage:
   307  //
   308  //	slice := g.Slice[int]{1, 2, 3, 4, 5}
   309  //	sum := slice.Iter().
   310  //		Fold(0,
   311  //			func(acc, val int) int {
   312  //				return acc + val
   313  //			})
   314  //	fmt.Println(sum)
   315  //
   316  // Output: 15.
   317  //
   318  // The resulting value will be the accumulation of elements based on the provided function.
   319  func (seq SeqSlice[V]) Fold(init V, fn func(acc, val V) V) V { return fold(seq, init, fn) }
   320  
   321  // ForEach iterates through all elements and applies the given function to each.
   322  //
   323  // The function applies the provided function to each element of the iterator.
   324  //
   325  // Params:
   326  //
   327  // - fn (func(V)): The function to apply to each element.
   328  //
   329  // Example usage:
   330  //
   331  //	iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
   332  //	iter.ForEach(func(val V) {
   333  //	    fmt.Println(val) // Replace this with the function logic you need.
   334  //	})
   335  //
   336  // The provided function will be applied to each element in the iterator.
   337  func (seq SeqSlice[V]) ForEach(fn func(v V)) {
   338  	seq(func(v V) bool {
   339  		fn(v)
   340  		return true
   341  	})
   342  }
   343  
   344  // Flatten flattens an iterator of iterators into a single iterator.
   345  //
   346  // The function creates a new iterator that flattens a sequence of iterators,
   347  // returning a single iterator containing elements from each iterator in sequence.
   348  //
   349  // Returns:
   350  //
   351  // - SeqSlice[V]: A single iterator containing elements from the sequence of iterators.
   352  //
   353  // Example usage:
   354  //
   355  //	nestedSlice := g.Slice[any]{
   356  //		1,
   357  //		g.SliceOf(2, 3),
   358  //		"abc",
   359  //		g.SliceOf("def", "ghi"),
   360  //		g.SliceOf(4.5, 6.7),
   361  //	}
   362  //
   363  //	nestedSlice.Iter().Flatten().Collect().Print()
   364  //
   365  // Output: Slice[1, 2, 3, abc, def, ghi, 4.5, 6.7]
   366  //
   367  // The resulting iterator will contain elements from each iterator in sequence.
   368  func (seq SeqSlice[V]) Flatten() SeqSlice[V] { return flatten(seq) }
   369  
   370  // Inspect creates a new iterator that wraps around the current iterator
   371  // and allows inspecting each element as it passes through.
   372  func (seq SeqSlice[V]) Inspect(fn func(v V)) SeqSlice[V] { return inspectSlice(seq, fn) }
   373  
   374  // Intersperse inserts the provided separator between elements of the iterator.
   375  //
   376  // The function creates a new iterator that inserts the given separator between each
   377  // consecutive pair of elements in the original iterator.
   378  //
   379  // Params:
   380  //
   381  // - sep (V): The separator to intersperse between elements.
   382  //
   383  // Returns:
   384  //
   385  // - SeqSlice[V]: An iterator containing elements with the separator interspersed.
   386  //
   387  // Example usage:
   388  //
   389  //	g.Slice[string]{"Hello", "World", "!"}.
   390  //		Iter().
   391  //		Intersperse(" ").
   392  //		Collect().
   393  //		Join().
   394  //		Print()
   395  //
   396  // Output: "Hello World !".
   397  //
   398  // The resulting iterator will contain elements with the separator interspersed.
   399  func (seq SeqSlice[V]) Intersperse(sep V) SeqSlice[V] { return intersperse(seq, sep) }
   400  
   401  // Map transforms each element in the iterator using the given function.
   402  //
   403  // The function creates a new iterator by applying the provided function to each element
   404  // of the original iterator.
   405  //
   406  // Params:
   407  //
   408  // - fn (func(V) V): The function used to transform elements.
   409  //
   410  // Returns:
   411  //
   412  // - SeqSlice[V]: A iterator containing elements transformed by the provided function.
   413  //
   414  // Example usage:
   415  //
   416  //	slice := g.Slice[int]{1, 2, 3}
   417  //	doubled := slice.
   418  //		Iter().
   419  //		Map(
   420  //			func(val int) int {
   421  //				return val * 2
   422  //			}).
   423  //		Collect()
   424  //	doubled.Print()
   425  //
   426  // Output: [2 4 6].
   427  //
   428  // The resulting iterator will contain elements transformed by the provided function.
   429  func (seq SeqSlice[V]) Map(transform func(V) V) SeqSlice[V] { return sliceMap(seq, transform) }
   430  
   431  // Partition divides the elements of the iterator into two separate slices based on a given predicate function.
   432  //
   433  // The function takes a predicate function 'fn', which should return true or false for each element in the iterator.
   434  // Elements for which 'fn' returns true are collected into the left slice, while those for which 'fn' returns false
   435  // are collected into the right slice.
   436  //
   437  // Params:
   438  //
   439  // - fn (func(V) bool): The predicate function used to determine the placement of elements.
   440  //
   441  // Returns:
   442  //
   443  // - (Slice[V], Slice[V]): Two slices representing elements that satisfy and don't satisfy the predicate, respectively.
   444  //
   445  // Example usage:
   446  //
   447  //	evens, odds := g.Slice[int]{1, 2, 3, 4, 5}.
   448  //		Iter().
   449  //		Partition(
   450  //			func(v int) bool {
   451  //				return v%2 == 0
   452  //			})
   453  //
   454  //	fmt.Println("Even numbers:", evens) // Output: Even numbers: Slice[2, 4]
   455  //	fmt.Println("Odd numbers:", odds)   // Output: Odd numbers: Slice[1, 3, 5]
   456  //
   457  // The resulting two slices will contain elements separated based on whether they satisfy the predicate or not.
   458  func (seq SeqSlice[V]) Partition(fn func(v V) bool) (Slice[V], Slice[V]) { return partition(seq, fn) }
   459  
   460  // Permutations generates iterators of all permutations of elements.
   461  //
   462  // The function uses a recursive approach to generate all the permutations of the elements.
   463  // If the iterator is empty or contains a single element, it returns the iterator itself
   464  // wrapped in a single-element iterator.
   465  //
   466  // Returns:
   467  //
   468  // - SeqSlices[V]: An iterator of iterators containing all possible permutations of the
   469  // elements in the iterator.
   470  //
   471  // Example usage:
   472  //
   473  //	slice := g.Slice[int]{1, 2, 3}
   474  //	perms := slice.Iter().Permutations().Collect()
   475  //	for _, perm := range perms {
   476  //	    fmt.Println(perm)
   477  //	}
   478  //
   479  // Output:
   480  //
   481  //	Slice[1, 2, 3]
   482  //	Slice[1, 3, 2]
   483  //	Slice[2, 1, 3]
   484  //	Slice[2, 3, 1]
   485  //	Slice[3, 1, 2]
   486  //	Slice[3, 2, 1]
   487  //
   488  // The resulting iterator will contain iterators representing all possible permutations
   489  // of the elements in the original iterator.
   490  func (seq SeqSlice[V]) Permutations() SeqSlices[V] { return permutations(seq) }
   491  
   492  // Range iterates through elements until the given function returns false.
   493  //
   494  // The function iterates through the elements of the iterator and applies the provided function
   495  // to each element. It stops iteration when the function returns false for an element.
   496  //
   497  // Params:
   498  //
   499  // - fn (func(V) bool): The function that evaluates elements for continuation of iteration.
   500  //
   501  // Example usage:
   502  //
   503  //	iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
   504  //	iter.Range(func(val int) bool {
   505  //	    fmt.Println(val) // Replace this with the function logic you need.
   506  //	    return val < 5 // Replace this with the condition for continuing iteration.
   507  //	})
   508  //
   509  // The iteration will stop when the provided function returns false for an element.
   510  func (seq SeqSlice[V]) Range(fn func(v V) bool) {
   511  	seq(func(v V) bool {
   512  		return fn(v)
   513  	})
   514  }
   515  
   516  // Skip returns a new iterator skipping the first n elements.
   517  //
   518  // The function creates a new iterator that skips the first n elements of the current iterator
   519  // and returns an iterator starting from the (n+1)th element.
   520  //
   521  // Params:
   522  //
   523  // - n (uint): The number of elements to skip from the beginning of the iterator.
   524  //
   525  // Returns:
   526  //
   527  // - SeqSlice[V]: An iterator that starts after skipping the first n elements.
   528  //
   529  // Example usage:
   530  //
   531  //	iter := g.Slice[int]{1, 2, 3, 4, 5, 6}.Iter()
   532  //	iter.Skip(3).Collect().Print()
   533  //
   534  // Output: [4, 5, 6]
   535  //
   536  // The resulting iterator will start after skipping the specified number of elements.
   537  func (seq SeqSlice[V]) Skip(n uint) SeqSlice[V] { return skipSlice(seq, n) }
   538  
   539  // StepBy creates a new iterator that iterates over every N-th element of the original iterator.
   540  // This function is useful when you want to skip a specific number of elements between each iteration.
   541  //
   542  // Parameters:
   543  // - n uint: The step size, indicating how many elements to skip between each iteration.
   544  //
   545  // Returns:
   546  // - SeqSlice[V]: A new iterator that produces elements from the original iterator with a step size of N.
   547  //
   548  // Example usage:
   549  //
   550  //	slice := g.Slice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
   551  //	iter := slice.Iter().StepBy(3)
   552  //	result := iter.Collect()
   553  //	result.Print()
   554  //
   555  // Output: [1 4 7 10]
   556  //
   557  // The resulting iterator will produce elements from the original iterator with a step size of N.
   558  func (seq SeqSlice[V]) StepBy(n uint) SeqSlice[V] { return stepbySlice(seq, n) }
   559  
   560  // SortBy applies a custom sorting function to the elements in the iterator
   561  // and returns a new iterator containing the sorted elements.
   562  //
   563  // The sorting function 'fn' should take two arguments, 'a' and 'b' of type V,
   564  // and return true if 'a' should be ordered before 'b', and false otherwise.
   565  //
   566  // Example:
   567  //
   568  //	g.SliceOf("a", "c", "b").
   569  //		Iter().
   570  //		SortBy(func(a, b string) cmp.Ordering { return b.Cmp(a) }).
   571  //		Collect().
   572  //		Print()
   573  //
   574  // Output: Slice[c, b, a]
   575  //
   576  // The returned iterator is of type SeqSlice[V], which implements the iterator
   577  // interface for further iteration over the sorted elements.
   578  func (seq SeqSlice[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqSlice[V] { return sortBySlice(seq, fn) }
   579  
   580  // Take returns a new iterator with the first n elements.
   581  // The function creates a new iterator containing the first n elements from the original iterator.
   582  func (seq SeqSlice[V]) Take(n uint) SeqSlice[V] { return takeSlice(seq, n) }
   583  
   584  // ToChan converts the iterator into a channel, optionally with context(s).
   585  //
   586  // The function converts the elements of the iterator into a channel for streaming purposes.
   587  // Optionally, it accepts context(s) to handle cancellation or timeout scenarios.
   588  //
   589  // Params:
   590  //
   591  // - ctxs (context.Context): Optional context(s) to control the channel behavior (e.g., cancellation).
   592  //
   593  // Returns:
   594  //
   595  // - chan V: A channel containing the elements from the iterator.
   596  //
   597  // Example usage:
   598  //
   599  //	iter := g.Slice[int]{1, 2, 3}.Iter()
   600  //	ctx, cancel := context.WithCancel(context.Background())
   601  //	defer cancel() // Ensure cancellation to avoid goroutine leaks.
   602  //	ch := iter.ToChan(ctx)
   603  //	for val := range ch {
   604  //	    fmt.Println(val)
   605  //	}
   606  //
   607  // The resulting channel allows streaming elements from the iterator with optional context handling.
   608  func (seq SeqSlice[V]) ToChan(ctxs ...context.Context) chan V {
   609  	ch := make(chan V)
   610  
   611  	ctx := context.Background()
   612  	if len(ctxs) != 0 {
   613  		ctx = ctxs[0]
   614  	}
   615  
   616  	go func() {
   617  		defer close(ch)
   618  
   619  		for v := range seq {
   620  			select {
   621  			case <-ctx.Done():
   622  				return
   623  			default:
   624  				ch <- v
   625  			}
   626  		}
   627  	}()
   628  
   629  	return ch
   630  }
   631  
   632  // Unique returns an iterator with only unique elements.
   633  //
   634  // The function returns an iterator containing only the unique elements from the original iterator.
   635  //
   636  // Returns:
   637  //
   638  // - SeqSlice[V]: An iterator containing unique elements from the original iterator.
   639  //
   640  // Example usage:
   641  //
   642  //	slice := g.Slice[int]{1, 2, 3, 2, 4, 5, 3}
   643  //	unique := slice.Iter().Unique().Collect()
   644  //	unique.Print()
   645  //
   646  // Output: [1, 2, 3, 4, 5].
   647  //
   648  // The resulting iterator will contain only unique elements from the original iterator.
   649  func (seq SeqSlice[V]) Unique() SeqSlice[V] { return uniqueSlice(seq) }
   650  
   651  // Zip combines elements from the current sequence and another sequence into pairs,
   652  // creating an ordered map with identical keys and values of type V.
   653  func (seq SeqSlice[V]) Zip(two SeqSlice[V]) SeqMapOrd[V, V] { return zip(seq, two) }
   654  
   655  // Find searches for an element in the iterator that satisfies the provided function.
   656  //
   657  // The function iterates through the elements of the iterator and returns the first element
   658  // for which the provided function returns true.
   659  //
   660  // Params:
   661  //
   662  // - fn (func(V) bool): The function used to test elements for a condition.
   663  //
   664  // Returns:
   665  //
   666  // - Option[V]: An Option containing the first element that satisfies the condition; None if not found.
   667  //
   668  // Example usage:
   669  //
   670  //	iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
   671  //
   672  //	found := iter.Find(
   673  //		func(i int) bool {
   674  //			return i == 2
   675  //		})
   676  //
   677  //	if found.IsSome() {
   678  //		fmt.Println("Found:", found.Some())
   679  //	} else {
   680  //		fmt.Println("Not found.")
   681  //	}
   682  //
   683  // The resulting Option may contain the first element that satisfies the condition, or None if not found.
   684  func (seq SeqSlice[V]) Find(fn func(v V) bool) Option[V] { return findSlice(seq, fn) }
   685  
   686  // Windows returns an iterator that yields sliding windows of elements of the specified size.
   687  //
   688  // The function creates a new iterator that yields windows of elements from the original iterator,
   689  // where each window is a slice containing elements of the specified size and moves one element at a time.
   690  //
   691  // Params:
   692  //
   693  // - n (int): The size of each window.
   694  //
   695  // Returns:
   696  //
   697  // - SeqSlices[V]: An iterator yielding sliding windows of elements of the specified size.
   698  //
   699  // Example usage:
   700  //
   701  //	slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
   702  //	windows := slice.Iter().Windows(3).Collect()
   703  //
   704  // Output: [Slice[1, 2, 3] Slice[2, 3, 4] Slice[3, 4, 5] Slice[4, 5, 6]]
   705  //
   706  // The resulting iterator will yield sliding windows of elements, each containing the specified number of elements.
   707  func (seq SeqSlice[V]) Windows(n Int) SeqSlices[V] { return windows(seq, n.Std()) }
   708  
   709  // FromChan converts a channel into an iterator.
   710  //
   711  // This function takes a channel as input and converts its elements into an iterator,
   712  // allowing seamless integration of channels into iterator-based processing pipelines.
   713  // It continuously reads from the channel until it's closed,
   714  // yielding each element to the provided yield function.
   715  //
   716  // Parameters:
   717  // - ch (<-chan V): The input channel to convert into an iterator.
   718  //
   719  // Returns:
   720  // - SeqSlice[V]: An iterator that yields elements from the channel.
   721  //
   722  // Example usage:
   723  //
   724  //	ch := make(chan int)
   725  //	go func() {
   726  //		defer close(ch)
   727  //		for i := 1; i <= 5; i++ {
   728  //			ch <- i
   729  //		}
   730  //	}()
   731  //
   732  //	// Convert the channel into an iterator and apply filtering and mapping operations.
   733  //	g.FromChan(ch).
   734  //		Filter(func(i int) bool { return i%2 == 0 }). // Filter even numbers.
   735  //		Map(func(i int) int { return i * 2 }).        // Double each element.
   736  //		Collect().                                    // Collect the results into a slice.
   737  //		Print()                                       // Print the collected results.
   738  //
   739  // Output: Slice[4, 8]
   740  //
   741  // The resulting iterator will yield elements from the provided channel, filtering out odd numbers,
   742  // doubling each even number, and finally collecting the results into a slice.
   743  func FromChan[V any](ch <-chan V) SeqSlice[V] {
   744  	return func(yield func(V) bool) {
   745  		for v := range ch {
   746  			if !yield(v) {
   747  				return
   748  			}
   749  		}
   750  	}
   751  }
   752  
   753  func ToSeqSlice[V any](slice []V) SeqSlice[V] {
   754  	return func(yield func(V) bool) {
   755  		for _, v := range slice {
   756  			if !yield(v) {
   757  				return
   758  			}
   759  		}
   760  	}
   761  }
   762  
   763  func chainSlice[V any](seqs ...SeqSlice[V]) SeqSlice[V] {
   764  	return func(yield func(V) bool) {
   765  		for _, seq := range seqs {
   766  			seq(func(v V) bool {
   767  				return yield(v)
   768  			})
   769  		}
   770  	}
   771  }
   772  
   773  func sliceMap[V, U any](seq SeqSlice[V], fn func(V) U) SeqSlice[U] {
   774  	return func(yield func(U) bool) {
   775  		seq(func(v V) bool {
   776  			return yield(fn(v))
   777  		})
   778  	}
   779  }
   780  
   781  func filterSlice[V any](seq SeqSlice[V], fn func(V) bool) SeqSlice[V] {
   782  	return func(yield func(V) bool) {
   783  		seq(func(v V) bool {
   784  			if fn(v) {
   785  				return yield(v)
   786  			}
   787  			return true
   788  		})
   789  	}
   790  }
   791  
   792  func excludeSlice[V any](seq SeqSlice[V], fn func(V) bool) SeqSlice[V] {
   793  	return filterSlice(seq, func(v V) bool { return !fn(v) })
   794  }
   795  
   796  func cycleSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
   797  	return func(yield func(V) bool) {
   798  		var saved []V
   799  
   800  		seq(func(v V) bool {
   801  			saved = append(saved, v)
   802  			return yield(v)
   803  		})
   804  
   805  		for len(saved) > 0 {
   806  			for _, v := range saved {
   807  				if !yield(v) {
   808  					return
   809  				}
   810  			}
   811  		}
   812  	}
   813  }
   814  
   815  func stepbySlice[V any](seq SeqSlice[V], n uint) SeqSlice[V] {
   816  	return func(yield func(V) bool) {
   817  		i := uint(0)
   818  		seq(func(v V) bool {
   819  			i++
   820  			if (i-1)%n == 0 {
   821  				return yield(v)
   822  			}
   823  			return true
   824  		})
   825  	}
   826  }
   827  
   828  func takeSlice[V any](seq SeqSlice[V], n uint) SeqSlice[V] {
   829  	return func(yield func(V) bool) {
   830  		seq(func(v V) bool {
   831  			if n == 0 {
   832  				return false
   833  			}
   834  			n--
   835  			return yield(v)
   836  		})
   837  	}
   838  }
   839  
   840  func uniqueSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
   841  	return func(yield func(V) bool) {
   842  		seen := NewSet[any]()
   843  		seq(func(v V) bool {
   844  			if !seen.Contains(v) {
   845  				seen.Add(v)
   846  				return yield(v)
   847  			}
   848  			return true
   849  		})
   850  	}
   851  }
   852  
   853  // works slower
   854  // func dedupSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
   855  // 	var current V
   856  
   857  // 	eq := f.Eqd[any]
   858  // 	if f.Comparable(current) {
   859  // 		eq = f.Eq
   860  // 	}
   861  
   862  // 	return func(yield func(V) bool) {
   863  // 		seq(func(v V) bool {
   864  // 			if eq(current)(v) {
   865  // 				return true
   866  // 			}
   867  
   868  // 			current = v
   869  // 			return yield(v)
   870  // 		})
   871  // 	}
   872  // }
   873  
   874  func dedupSlice[V any](seq SeqSlice[V]) SeqSlice[V] {
   875  	var current V
   876  	comparable := f.Comparable(current)
   877  
   878  	return func(yield func(V) bool) {
   879  		seq(func(v V) bool {
   880  			if comparable {
   881  				if f.Eq[any](current)(v) {
   882  					return true
   883  				}
   884  			} else {
   885  				if f.Eqd(current)(v) {
   886  					return true
   887  				}
   888  			}
   889  
   890  			current = v
   891  			return yield(v)
   892  		})
   893  	}
   894  }
   895  
   896  func sortBySlice[V any](seq SeqSlice[V], fn func(a, b V) cmp.Ordering) SeqSlice[V] {
   897  	items := seq.Collect()
   898  	items.SortBy(fn)
   899  
   900  	return items.Iter()
   901  }
   902  
   903  func skipSlice[V any](seq SeqSlice[V], n uint) SeqSlice[V] {
   904  	return func(yield func(V) bool) {
   905  		seq(func(v V) bool {
   906  			if n > 0 {
   907  				n--
   908  				return true
   909  			}
   910  			return yield(v)
   911  		})
   912  	}
   913  }
   914  
   915  func inspectSlice[V any](seq SeqSlice[V], fn func(V)) SeqSlice[V] {
   916  	return func(yield func(V) bool) {
   917  		seq(func(v V) bool {
   918  			fn(v)
   919  			return yield(v)
   920  		})
   921  	}
   922  }
   923  
   924  func enumerate[V any](seq SeqSlice[V]) SeqMapOrd[Int, V] {
   925  	return func(yield func(Int, V) bool) {
   926  		i := Int(-1)
   927  		seq(func(v V) bool {
   928  			i++
   929  			return yield(i, v)
   930  		})
   931  	}
   932  }
   933  
   934  func zip[V, U any](one SeqSlice[V], two SeqSlice[U]) SeqMapOrd[V, U] {
   935  	return func(yield func(V, U) bool) {
   936  		oneNext, oneStop := one.Pull()
   937  		defer oneStop()
   938  
   939  		twoNext, twoStop := two.Pull()
   940  		defer twoStop()
   941  
   942  		for {
   943  			one, ok := oneNext()
   944  			if !ok {
   945  				return
   946  			}
   947  
   948  			two, ok := twoNext()
   949  			if !ok {
   950  				return
   951  			}
   952  
   953  			if !yield(one, two) {
   954  				return
   955  			}
   956  		}
   957  	}
   958  }
   959  
   960  func fold[V any](seq SeqSlice[V], init V, fn func(V, V) V) V {
   961  	seq(func(v V) bool {
   962  		init = fn(init, v)
   963  		return true
   964  	})
   965  	return init
   966  }
   967  
   968  func findSlice[V any](seq SeqSlice[V], fn func(V) bool) (r Option[V]) {
   969  	seq(func(v V) bool {
   970  		if !fn(v) {
   971  			return true
   972  		}
   973  		r = Some(v)
   974  		return false
   975  	})
   976  
   977  	return r
   978  }
   979  
   980  func chunks[V any](seq SeqSlice[V], n int) SeqSlices[V] {
   981  	return func(yield func([]V) bool) {
   982  		buf := make([]V, 0, n)
   983  
   984  		seq(func(v V) bool {
   985  			if len(buf) == n {
   986  				clear(buf)
   987  				buf = buf[:0]
   988  			}
   989  
   990  			if len(buf) < n-1 {
   991  				buf = append(buf, v)
   992  				return true
   993  			}
   994  
   995  			if len(buf) < n {
   996  				buf = append(buf, v)
   997  				return yield(buf)
   998  			}
   999  
  1000  			return yield(buf)
  1001  		})
  1002  
  1003  		if len(buf) < n {
  1004  			yield(buf)
  1005  		}
  1006  	}
  1007  }
  1008  
  1009  func windows[V any](seq SeqSlice[V], n int) SeqSlices[V] {
  1010  	return func(yield func([]V) bool) {
  1011  		buf := make([]V, 0, n)
  1012  
  1013  		seq(func(v V) bool {
  1014  			if len(buf) < n-1 {
  1015  				buf = append(buf, v)
  1016  				return true
  1017  			}
  1018  			if len(buf) < n {
  1019  				buf = append(buf, v)
  1020  				return yield(buf)
  1021  			}
  1022  
  1023  			copy(buf, buf[1:])
  1024  			buf[len(buf)-1] = v
  1025  			return yield(buf)
  1026  		})
  1027  
  1028  		if len(buf) < n {
  1029  			yield(buf)
  1030  		}
  1031  	}
  1032  }
  1033  
  1034  func combinationIndices(n, k int) iter.Seq[[]int] {
  1035  	return func(yield func([]int) bool) {
  1036  		if k > n || k < 1 || n < 0 {
  1037  			return
  1038  		}
  1039  
  1040  		indices := make([]int, k)
  1041  		for i := range indices {
  1042  			indices[i] = i
  1043  		}
  1044  
  1045  		for {
  1046  			if !yield(indices) {
  1047  				return
  1048  			}
  1049  
  1050  			i := k - 1
  1051  			for i >= 0 && indices[i] == i+n-k {
  1052  				i--
  1053  			}
  1054  
  1055  			if i < 0 {
  1056  				return
  1057  			}
  1058  
  1059  			indices[i]++
  1060  			for j := i + 1; j < k; j++ {
  1061  				indices[j] = indices[j-1] + 1
  1062  			}
  1063  		}
  1064  	}
  1065  }
  1066  
  1067  func combinations[V any](seq SeqSlice[V], n int) SeqSlices[V] {
  1068  	return func(yield func([]V) bool) {
  1069  		s := seq.Collect()
  1070  		for indices := range combinationIndices(len(s), n) {
  1071  			buf := make([]V, n)
  1072  			for i, v := range indices {
  1073  				buf[i] = s[v]
  1074  			}
  1075  			if !yield(buf) {
  1076  				return
  1077  			}
  1078  		}
  1079  	}
  1080  }
  1081  
  1082  func permutationIndices(n int) iter.Seq[[]int] {
  1083  	return func(yield func([]int) bool) {
  1084  		indices := make([]int, n)
  1085  		for i := range indices {
  1086  			indices[i] = i
  1087  		}
  1088  
  1089  		for {
  1090  			if !yield(indices) {
  1091  				return
  1092  			}
  1093  
  1094  			i := n - 1
  1095  			for i > 0 && indices[i-1] >= indices[i] {
  1096  				i--
  1097  			}
  1098  
  1099  			if i <= 0 {
  1100  				return
  1101  			}
  1102  
  1103  			j := n - 1
  1104  			for indices[j] <= indices[i-1] {
  1105  				j--
  1106  			}
  1107  
  1108  			indices[i-1], indices[j] = indices[j], indices[i-1]
  1109  
  1110  			for x, y := i, n-1; x < y; x, y = x+1, y-1 {
  1111  				indices[x], indices[y] = indices[y], indices[x]
  1112  			}
  1113  		}
  1114  	}
  1115  }
  1116  
  1117  func permutations[V any](seq SeqSlice[V]) SeqSlices[V] {
  1118  	return func(yield func([]V) bool) {
  1119  		s := seq.Collect()
  1120  		for indices := range permutationIndices(len(s)) {
  1121  			buf := make([]V, len(s))
  1122  			for i, v := range indices {
  1123  				buf[i] = s[v]
  1124  			}
  1125  			if !yield(buf) {
  1126  				return
  1127  			}
  1128  		}
  1129  	}
  1130  }
  1131  
  1132  func flatten[V any](seq SeqSlice[V]) SeqSlice[V] {
  1133  	return func(yield func(V) bool) {
  1134  		seq(func(s V) bool {
  1135  			if reflect.TypeOf(s).Kind() == reflect.Slice {
  1136  				flattenSlice(s, yield)
  1137  			} else {
  1138  				yield(s)
  1139  			}
  1140  			return true
  1141  		})
  1142  	}
  1143  }
  1144  
  1145  func flattenSlice[V any](s V, yield func(V) bool) {
  1146  	val := reflect.ValueOf(s)
  1147  
  1148  	for i := 0; i < val.Len(); i++ {
  1149  		elem := val.Index(i)
  1150  		if elem.Kind() == reflect.Interface {
  1151  			elem = elem.Elem()
  1152  		}
  1153  
  1154  		if elem.Kind() == reflect.Slice {
  1155  			flattenSlice(elem.Interface().(V), yield)
  1156  		} else {
  1157  			if !yield(elem.Interface().(V)) {
  1158  				return
  1159  			}
  1160  		}
  1161  	}
  1162  }
  1163  
  1164  func countSlice[V any](seq SeqSlice[V]) Int {
  1165  	var counter Int
  1166  	seq(func(V) bool {
  1167  		counter++
  1168  		return true
  1169  	})
  1170  
  1171  	return counter
  1172  }
  1173  
  1174  func counterSlice[V any](seq SeqSlice[V]) SeqMapOrd[V, Int] {
  1175  	result := NewMapOrd[V, Int]()
  1176  	seq(func(v V) bool {
  1177  		r := result.Get(v).UnwrapOrDefault()
  1178  		r++
  1179  		result.Set(v, r)
  1180  		return true
  1181  	})
  1182  
  1183  	return result.Iter()
  1184  }
  1185  
  1186  func partition[V any](seq SeqSlice[V], fn func(V) bool) (Slice[V], Slice[V]) {
  1187  	left, right := make([]V, 0), make([]V, 0)
  1188  	seq(func(v V) bool {
  1189  		if fn(v) {
  1190  			left = append(left, v)
  1191  		} else {
  1192  			right = append(right, v)
  1193  		}
  1194  		return true
  1195  	})
  1196  
  1197  	return left, right
  1198  }
  1199  
  1200  func intersperse[V any](seq SeqSlice[V], sep V) SeqSlice[V] {
  1201  	return func(yield func(V) bool) {
  1202  		first := true
  1203  
  1204  		seq(func(v V) bool {
  1205  			if !first && !yield(sep) {
  1206  				return false
  1207  			}
  1208  
  1209  			first = false
  1210  			if !yield(v) {
  1211  				return false
  1212  			}
  1213  
  1214  			return true
  1215  		})
  1216  	}
  1217  }