Source File
iter.go
Belonging Package
slices
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package slices
import (
)
// All returns an iterator over index-value pairs in the slice
// in the usual order.
func [ ~[], any]( ) iter.Seq2[int, ] {
return func( func(int, ) bool) {
for , := range {
if !(, ) {
return
}
}
}
}
// Backward returns an iterator over index-value pairs in the slice,
// traversing it backward with descending indices.
func [ ~[], any]( ) iter.Seq2[int, ] {
return func( func(int, ) bool) {
for := len() - 1; >= 0; -- {
if !(, []) {
return
}
}
}
}
// Values returns an iterator that yields the slice elements in order.
func [ ~[], any]( ) iter.Seq[] {
return func( func() bool) {
for , := range {
if !() {
return
}
}
}
}
// AppendSeq appends the values from seq to the slice and
// returns the extended slice.
// If seq is empty, the result preserves the nilness of s.
func [ ~[], any]( , iter.Seq[]) {
for := range {
= append(, )
}
return
}
// Collect collects values from seq into a new slice and returns it.
// If seq is empty, the result is nil.
func [ any]( iter.Seq[]) [] {
return AppendSeq([](nil), )
}
// Sorted collects values from seq into a new slice, sorts the slice,
// and returns it.
// If seq is empty, the result is nil.
func [ cmp.Ordered]( iter.Seq[]) [] {
:= Collect()
Sort()
return
}
// SortedFunc collects values from seq into a new slice, sorts the slice
// using the comparison function, and returns it.
// If seq is empty, the result is nil.
func [ any]( iter.Seq[], func(, ) int) [] {
:= Collect()
SortFunc(, )
return
}
// SortedStableFunc collects values from seq into a new slice.
// It then sorts the slice while keeping the original order of equal elements,
// using the comparison function to compare elements.
// It returns the new slice.
// If seq is empty, the result is nil.
func [ any]( iter.Seq[], func(, ) int) [] {
:= Collect()
SortStableFunc(, )
return
}
// Chunk returns an iterator over consecutive sub-slices of up to n elements of s.
// All but the last sub-slice will have size n.
// All sub-slices are clipped to have no capacity beyond the length.
// If s is empty, the sequence is empty: there is no empty slice in the sequence.
// Chunk panics if n is less than 1.
func [ ~[], any]( , int) iter.Seq[] {
if < 1 {
panic("cannot be less than 1")
}
return func( func() bool) {
for := 0; < len(); += {
// Clamp the last chunk to the slice bound as necessary.
:= min(, len([:]))
// Set the capacity of each chunk so that appending to a chunk does
// not modify the original slice.
if !([ : + : +]) {
return
}
}
}
}
![]() |
The pages are generated with Golds v0.7.7-preview. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |