g

package module
v1.0.194 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 28, 2025 License: MIT Imports: 51 Imported by: 36

README

🤪 G: Go Crazy, Go G, Go Nuts!

Go Reference Go Report Card Coverage Status Go Ask DeepWiki

Introducing G, the wackiest Go package on the planet, created to make your coding experience an absolute riot! With G, you can forget about dull and monotonous code, we're all about turning the mundane into the insanely hilarious. It's not just a bicycle, it's almost a motorcycle 🤣!

🎉 What's in the box?

  1. 📖 Readable syntax: Boring code is so yesterday! G turns your code into a party by blending seamlessly with Go and making it super clean and laughably maintainable.
  2. 🔀 Encoding and decoding: Juggling data formats? No problemo! G's got your back with Base64, URL, Gzip, and Rot13 support. Encode and decode like a pro!
  3. 🔒 Hashing extravaganza: Safety first, right? Hash your data with MD5, SHA1, SHA256, or SHA512, and enjoy peace of mind while G watches over your bytes.
  4. 📁 File and directory shenanigans: Create, read, write, and dance through files and directories with G's fun-tastic functions. Trust us, managing files has never been this entertaining.
  5. 🌈 Data type compatibility: Strings, integers, floats, bytes, slices, maps, you name it! G is the life of the party, mingling with all your favorite data types.
  6. 🔧 Customize and extend: Need something extra? G is your best buddy, ready to be extended or modified to suit any project.
  7. 📚 Docs & examples: We're not just about fun and games, we've got detailed documentation and examples that'll have you smiling from ear to ear as you learn the G way.

Take your Go projects to a whole new level of excitement with G! It's time to stop coding like it's a chore and start coding like it's a celebration! 🥳

Examples

Generate a securely random string.

stdlib g
func main() {
	const charset = "abcdefghijklmnopqrstuvwxyz" +
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

	length := 10

	b := make([]byte, length)
	if _, err := rand.Read(b); err != nil {
		return
	}

	for i, v := range b {
		b[i] = charset[v%byte(len(charset))]
	}

	result := string(b)
	fmt.Println(result)
}
func main() {
	result := g.NewString().Random(10)
	fmt.Println(result)
}

GetOrDefault returns the value for a key. If the key does not exist, returns the default value instead. This function is useful when you want to provide a fallback value for keys that may not be present in the map.

stdlib g
func main() {
	md := make(map[int][]int)

	for i := range 5 {
		md[i] = append(md[i], i)
	}

	fmt.Println(md)
}
func main() {
	md := g.NewMap[int, g.Slice[int]]()

	for i := range 5 {
		md.Set(i, md.Get(i).UnwrapOrDefault().Append(i))
	}

    // or

	for i := range 5 {
		entry := md.Entry(i)
		entry.OrDefault() // Insert an empty slice if missing
		entry.Transform(
			func(s Slice[int]) Slice[int] {
				return s.Append(i) // Append the current index to the slice
			})
	}

	fmt.Println(md)
}

Copy copies the contents of the current directory to the destination directory.

stdlib g
func copyDir(src, dest string) error {
	return filepath.Walk(src, func(path string,
		info fs.FileInfo, err error,
	) error {
		if err != nil {
			return err
		}

		relPath, err := filepath.Rel(src, path)
		if err != nil {
			return err
		}

		destPath := filepath.Join(dest, relPath)

		if info.IsDir() {
			return os.MkdirAll(destPath, info.Mode())
		}

		return copyFile(path, destPath, info.Mode())
	})
}

func copyFile(src, dest string, mode fs.FileMode) error {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	destFile, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, mode)
	if err != nil {
		return err
	}
	defer destFile.Close()

	_, err = io.Copy(destFile, srcFile)

	return err
}

func main() {
	src := "path/to/source/directory"
	dest := "path/to/destination/directory"

	err := copyDir(src, dest)
	if err != nil {
		fmt.Println("Error copying directory:", err)
	} else {
		fmt.Println("Directory copied successfully")
	}
}
func main() {
	g.NewDir(".").Copy("copy").Unwrap()
}

RandomSample returns a new slice containing a random sample of elements from the original slice.

stdlib g
func RandomSample(slice []int, amount int) []int {
	if amount > len(slice) {
		amount = len(slice)
	}

	samples := make([]int, amount)

	for i := 0; i < amount; i++ {
		index, _ := rand.Int(rand.Reader, big.NewInt(int64(len(slice))))
		samples[i] = slice[index.Int64()]
		slice = append(slice[:index.Int64()], slice[index.Int64()+1:]...)
	}

	return samples
}

func main() {
	slice := []int{1, 2, 3, 4, 5, 6}
	samples := RandomSample(slice, 3)
	fmt.Println(samples)
}
func main() {
	slice := g.SliceOf(1, 2, 3, 4, 5, 6)
	samples := slice.RandomSample(3)
	fmt.Println(samples)
}

Documentation

Index

Constants

View Source
const (
	ASCII_LETTERS   String = ASCII_LOWERCASE + ASCII_UPPERCASE
	ASCII_LOWERCASE String = "abcdefghijklmnopqrstuvwxyz"
	ASCII_UPPERCASE String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	DIGITS          String = "0123456789"
	HEXDIGITS       String = "0123456789abcdefABCDEF"
	OCTDIGITS       String = "01234567"
	PUNCTUATION     String = `!"#$%&'()*+,-./:;<=>?@[\]^{|}~` + "`"

	FileDefault os.FileMode = 0o644
	FileCreate  os.FileMode = 0o666
	DirDefault  os.FileMode = 0o755
	FullAccess  os.FileMode = 0o777

	PathSeperator = String(os.PathSeparator)
)

Variables

This section is empty.

Functions

func Errorf added in v1.0.146

func Errorf[T ~string](format T, args ...any) error

Errorf formats according to a format specifier and returns it as an error.

Example:

err := g.Errorf("could not open {}: {}", filename, err)
if err != nil { /* ... */ }

Types

type Builder added in v1.0.62

type Builder struct {
	// contains filtered or unexported fields
}

Builder wraps strings.Builder and provides additional type-safe methods for use with the custom types String and Int.

func NewBuilder added in v1.0.62

func NewBuilder() *Builder

NewBuilder creates a new instance of Builder.

func (*Builder) Cap added in v1.0.62

func (b *Builder) Cap() Int

Cap returns the builder’s current capacity.

func (*Builder) Grow added in v1.0.62

func (b *Builder) Grow(n Int)

Grow increases the builder’s capacity by at least n bytes.

func (*Builder) Len added in v1.0.62

func (b *Builder) Len() Int

Len returns the number of bytes currently in the builder.

func (*Builder) Reset added in v1.0.62

func (b *Builder) Reset()

Reset clears the contents of the builder.

func (*Builder) String added in v1.0.62

func (b *Builder) String() String

String returns the accumulated string as a custom String type.

func (*Builder) Write added in v1.0.62

func (b *Builder) Write(bs []byte) (int, error)

Write appends the given byte slice to the builder.

func (*Builder) WriteByte added in v1.0.62

func (b *Builder) WriteByte(c byte) error

WriteByte appends the given byte to the builder.

func (*Builder) WriteRune added in v1.0.62

func (b *Builder) WriteRune(r rune) (int, error)

WriteRune appends the given rune to the builder.

func (*Builder) WriteString added in v1.0.124

func (b *Builder) WriteString(str String) (int, error)

WriteString appends the given String to the builder.

type Bytes

type Bytes []byte

Bytes is an alias for the []byte type.

func NewBytes

func NewBytes(size ...Int) Bytes

NewBytes creates a new Bytes value.

func (Bytes) Append added in v1.0.164

func (bs Bytes) Append(obs Bytes) Bytes

Append appends the given Bytes to the current Bytes.

func (Bytes) Clone

func (bs Bytes) Clone() Bytes

Clone creates a new Bytes instance with the same content as the current Bytes.

func (Bytes) Cmp added in v1.0.70

func (bs Bytes) Cmp(obs Bytes) cmp.Ordering

Cmp compares the Bytes with another Bytes and returns an cmp.Ordering.

func (Bytes) Contains

func (bs Bytes) Contains(obs Bytes) bool

Contains checks if the Bytes contains the specified Bytes.

func (Bytes) ContainsAll

func (bs Bytes) ContainsAll(obss ...Bytes) bool

ContainsAll checks if the Bytes contains all of the specified Bytes.

func (Bytes) ContainsAny

func (bs Bytes) ContainsAny(obss ...Bytes) bool

ContainsAny checks if the Bytes contains any of the specified Bytes.

func (Bytes) ContainsAnyChars

func (bs Bytes) ContainsAnyChars(chars String) bool

ContainsAnyChars checks if the given Bytes contains any characters from the input String.

func (Bytes) ContainsRune

func (bs Bytes) ContainsRune(r rune) bool

ContainsRune checks if the Bytes contains the specified rune.

func (Bytes) Count

func (bs Bytes) Count(obs Bytes) Int

Count counts the number of occurrences of the specified Bytes in the Bytes.

func (Bytes) Empty

func (bs Bytes) Empty() bool

Empty checks if the Bytes is empty.

func (Bytes) Eq

func (bs Bytes) Eq(obs Bytes) bool

Eq checks if the Bytes is equal to another Bytes.

func (Bytes) EqFold

func (bs Bytes) EqFold(obs Bytes) bool

EqFold compares two Bytes slices case-insensitively.

func (Bytes) Fields added in v1.0.77

func (bs Bytes) Fields() SeqSlice[Bytes]

Fields splits the Bytes into a slice of substrings, removing any whitespace, and returns the iterator.

func (Bytes) FieldsBy added in v1.0.77

func (bs Bytes) FieldsBy(fn func(r rune) bool) SeqSlice[Bytes]

FieldsBy splits the Bytes into a slice of substrings using a custom function to determine the field boundaries, and returns the iterator.

func (Bytes) FloatBE added in v1.0.180

func (bs Bytes) FloatBE() Float

FloatBE interprets the Bytes as an IEEE-754 64-bit float in BigEndian order. If the Bytes length is not exactly 8, returns 0.

func (Bytes) FloatLE added in v1.0.180

func (bs Bytes) FloatLE() Float

FloatLE interprets the Bytes as an IEEE-754 64-bit float in LittleEndian order. If the Bytes length is not exactly 8, returns 0.

func (Bytes) Gt

func (bs Bytes) Gt(obs Bytes) bool

Gt checks if the Bytes is greater than another Bytes.

func (Bytes) Hash

func (bs Bytes) Hash() bhash

Hash returns a bhash struct wrapping the given Bytes.

func (Bytes) Index

func (bs Bytes) Index(obs Bytes) Int

Index returns the index of the first instance of obs in bs, or -1 if bs is not present in obs.

func (Bytes) IndexByte

func (bs Bytes) IndexByte(b byte) Int

IndexByte returns the index of the first instance of the byte b in bs, or -1 if b is not present in bs.

func (Bytes) IndexRune

func (bs Bytes) IndexRune(r rune) Int

IndexRune returns the index of the first instance of the rune r in bs, or -1 if r is not present in bs.

func (Bytes) IntBE added in v1.0.179

func (bs Bytes) IntBE() Int

IntBE interprets the Bytes as a signed 64-bit integer in BigEndian order. If the Bytes length is less than 8, it is padded with leading zeros. If the Bytes length is greater than 8, only the last 8 bytes are used.

func (Bytes) IntLE added in v1.0.179

func (bs Bytes) IntLE() Int

IntLE interprets the Bytes as a signed 64-bit integer in LittleEndian order. If the Bytes length is less than 8, it is padded with trailing zeros. If the Bytes length is greater than 8, only the first 8 bytes are used.

func (Bytes) LastIndex

func (bs Bytes) LastIndex(obs Bytes) Int

LastIndex returns the index of the last instance of obs in bs, or -1 if obs is not present in bs.

func (Bytes) LastIndexByte

func (bs Bytes) LastIndexByte(b byte) Int

LastIndexByte returns the index of the last instance of the byte b in bs, or -1 if b is not present in bs.

func (Bytes) Len

func (bs Bytes) Len() Int

Len returns the length of the Bytes.

func (Bytes) LenRunes

func (bs Bytes) LenRunes() Int

LenRunes returns the number of runes in the Bytes.

func (Bytes) Lower

func (bs Bytes) Lower() Bytes

Lower converts the Bytes to lowercase.

func (Bytes) Lt

func (bs Bytes) Lt(obs Bytes) bool

Lt checks if the Bytes is less than another Bytes.

func (Bytes) Map

func (bs Bytes) Map(fn func(rune) rune) Bytes

Map applies a function to each rune in the Bytes and returns the modified Bytes.

func (Bytes) Ne

func (bs Bytes) Ne(obs Bytes) bool

Ne checks if the Bytes is not equal to another Bytes.

func (Bytes) NormalizeNFC

func (bs Bytes) NormalizeNFC() Bytes

NormalizeNFC returns a new Bytes with its Unicode characters normalized using the NFC form.

func (Bytes) NotEmpty

func (bs Bytes) NotEmpty() bool

NotEmpty checks if the Bytes is not empty.

func (Bytes) Prepend added in v1.0.164

func (bs Bytes) Prepend(obs Bytes) Bytes

Prepend prepends the given Bytes to the current Bytes.

func (Bytes) Print

func (bs Bytes) Print() Bytes

Print writes the content of the Bytes to the standard output (console) and returns the Bytes unchanged.

func (Bytes) Println added in v1.0.122

func (bs Bytes) Println() Bytes

Println writes the content of the Bytes to the standard output (console) with a newline and returns the Bytes unchanged.

func (Bytes) Reader

func (bs Bytes) Reader() *bytes.Reader

Reader returns a *bytes.Reader initialized with the content of Bytes.

func (Bytes) Regexp added in v1.0.123

func (bs Bytes) Regexp() regexpb

Regexp wraps a Bytes into an re struct to provide regex-related methods.

func (Bytes) Repeat

func (bs Bytes) Repeat(count Int) Bytes

Repeat returns a new Bytes consisting of the current Bytes repeated 'count' times.

func (Bytes) Replace

func (bs Bytes) Replace(oldB, newB Bytes, n Int) Bytes

Replace replaces the first 'n' occurrences of 'oldB' with 'newB' in the Bytes.

func (Bytes) ReplaceAll

func (bs Bytes) ReplaceAll(oldB, newB Bytes) Bytes

ReplaceAll replaces all occurrences of 'oldB' with 'newB' in the Bytes.

func (*Bytes) Reset added in v1.0.148

func (bs *Bytes) Reset()

Reset resets the length of the Bytes slice to zero, preserving its capacity.

func (Bytes) Reverse

func (bs Bytes) Reverse() Bytes

Reverse reverses bytes for ASCII or invalid UTF-8 for valid UTF-8 it reverses by runes.

func (Bytes) Runes added in v1.0.81

func (bs Bytes) Runes() []rune

Runes returns the Bytes as a slice of runes.

func (Bytes) Split

func (bs Bytes) Split(sep ...Bytes) SeqSlice[Bytes]

Split splits the Bytes by the specified separator and returns the iterator.

func (Bytes) SplitAfter added in v1.0.77

func (bs Bytes) SplitAfter(sep Bytes) SeqSlice[Bytes]

SplitAfter splits the Bytes after each instance of the specified separator and returns the iterator.

func (Bytes) Std

func (bs Bytes) Std() []byte

Std returns the Bytes as a byte slice.

func (Bytes) String added in v1.0.81

func (bs Bytes) String() String

String returns the Bytes as an String.

func (Bytes) StringUnsafe added in v1.0.147

func (bs Bytes) StringUnsafe() String

StringUnsafe converts the Bytes into a String without copying memory. Warning: the resulting String shares the same underlying memory as the original Bytes. If the Bytes is modified later, the String will reflect those changes and may cause undefined behavior.

func (Bytes) StripPrefix added in v1.0.81

func (bs Bytes) StripPrefix(cutset Bytes) Bytes

StripPrefix trims the specified Bytes prefix from the Bytes.

func (Bytes) StripSuffix added in v1.0.81

func (bs Bytes) StripSuffix(cutset Bytes) Bytes

StripSuffix trims the specified Bytes suffix from the Bytes.

func (Bytes) Title

func (bs Bytes) Title() Bytes

Title converts the Bytes to title case.

func (Bytes) Transform added in v1.0.89

func (bs Bytes) Transform(fn func(Bytes) Bytes) Bytes

Transform applies a transformation function to the Bytes and returns the result.

func (Bytes) Trim

func (bs Bytes) Trim() Bytes

Trim trims leading and trailing white space from the Bytes.

func (Bytes) TrimEnd added in v1.0.81

func (bs Bytes) TrimEnd() Bytes

TrimEnd removes trailing white space from the Bytes.

func (Bytes) TrimEndSet added in v1.0.82

func (bs Bytes) TrimEndSet(cutset String) Bytes

TrimEndSet removes the specified set of characters from the end of the Bytes.

func (Bytes) TrimSet added in v1.0.82

func (bs Bytes) TrimSet(cutset String) Bytes

TrimSet trims the specified set of characters from both the beginning and end of the Bytes.

func (Bytes) TrimStart added in v1.0.81

func (bs Bytes) TrimStart() Bytes

TrimStart removes leading white space from the Bytes.

func (Bytes) TrimStartSet added in v1.0.82

func (bs Bytes) TrimStartSet(cutset String) Bytes

TrimStartSet removes the specified set of characters from the beginning of the Bytes.

func (Bytes) Upper

func (bs Bytes) Upper() Bytes

Upper converts the Bytes to uppercase.

type Deque added in v1.0.181

type Deque[T any] struct {
	// contains filtered or unexported fields
}

Deque is a double-ended queue implemented with a growable ring buffer. It provides efficient insertion and removal of elements at both ends.

func DequeOf added in v1.0.181

func DequeOf[T any](elements ...T) *Deque[T]

DequeOf creates a new Deque containing the provided elements.

func NewDeque added in v1.0.181

func NewDeque[T any](capacity ...Int) *Deque[T]

NewDeque creates a new Deque of the given generic type T with the specified capacity. The capacity parameter specifies the initial capacity of the underlying slice. If no capacity is provided, an empty Deque with a capacity of 0 is returned.

Parameters:

- capacity ...Int: An optional parameter specifying the initial capacity of the Deque

Returns:

- Deque[T]: A new Deque of the specified generic type T with the given capacity

Example usage:

d1 := g.NewDeque[int]()     // Creates an empty Deque of type int
d2 := g.NewDeque[int](10)   // Creates an empty Deque with capacity of 10

func (*Deque[T]) Back added in v1.0.181

func (dq *Deque[T]) Back() Option[T]

Back returns a reference to the last element. Returns None if the Deque is empty.

func (*Deque[T]) BinarySearch added in v1.0.181

func (dq *Deque[T]) BinarySearch(value T, fn func(T, T) cmp.Ordering) (Int, bool)

BinarySearch searches for a value in a sorted Deque using binary search. Returns the index where the value is found, or where it should be inserted.

func (*Deque[T]) Capacity added in v1.0.181

func (dq *Deque[T]) Capacity() Int

Capacity returns the current capacity of the Deque.

func (*Deque[T]) Clear added in v1.0.181

func (dq *Deque[T]) Clear()

Clear removes all elements from the Deque.

func (*Deque[T]) Clone added in v1.0.181

func (dq *Deque[T]) Clone() *Deque[T]

Clone creates a deep copy of the Deque.

func (*Deque[T]) Contains added in v1.0.181

func (dq *Deque[T]) Contains(value T) bool

Contains checks if the Deque contains the specified value.

func (*Deque[T]) Eq added in v1.0.181

func (dq *Deque[T]) Eq(other *Deque[T]) bool

Eq checks if two Deques are equal.

func (*Deque[T]) Front added in v1.0.181

func (dq *Deque[T]) Front() Option[T]

Front returns a reference to the first element. Returns None if the Deque is empty.

func (*Deque[T]) Get added in v1.0.181

func (dq *Deque[T]) Get(index Int) Option[T]

Get retrieves an element at the specified index. Index 0 represents the front of the Deque. Returns None if the index is out of bounds.

func (*Deque[T]) Index added in v1.0.181

func (dq *Deque[T]) Index(value T) Int

Index returns the index of the first occurrence of the specified value, or -1 if not found.

func (*Deque[T]) Insert added in v1.0.181

func (dq *Deque[T]) Insert(index Int, value T)

Insert inserts an element at the specified index. Index 0 represents the front of the Deque. Panics if the index is out of bounds.

func (*Deque[T]) IsEmpty added in v1.0.181

func (dq *Deque[T]) IsEmpty() bool

IsEmpty returns true if the Deque contains no elements.

func (*Deque[T]) Iter added in v1.0.181

func (dq *Deque[T]) Iter() SeqDeque[T]

Iter returns an iterator for the Deque, allowing for sequential iteration over its elements from front to back.

func (*Deque[T]) IterReverse added in v1.0.181

func (dq *Deque[T]) IterReverse() SeqDeque[T]

IterReverse returns an iterator for the Deque that allows for sequential iteration over its elements in reverse order (from back to front).

func (*Deque[T]) Len added in v1.0.181

func (dq *Deque[T]) Len() Int

Len returns the number of elements in the Deque.

func (*Deque[T]) MakeContiguous added in v1.0.181

func (dq *Deque[T]) MakeContiguous() Slice[T]

MakeContiguous rearranges the internal storage of the Deque so that its elements are in contiguous memory. Returns a slice that contains all elements.

func (*Deque[T]) PopBack added in v1.0.181

func (dq *Deque[T]) PopBack() Option[T]

PopBack removes and returns the last element of the Deque. Returns None if the Deque is empty.

func (*Deque[T]) PopFront added in v1.0.181

func (dq *Deque[T]) PopFront() Option[T]

PopFront removes and returns the first element of the Deque. Returns None if the Deque is empty.

func (*Deque[T]) Print added in v1.0.181

func (dq *Deque[T]) Print() *Deque[T]

Print writes the elements of the Deque to the standard output (console) and returns the Deque unchanged.

func (*Deque[T]) Println added in v1.0.181

func (dq *Deque[T]) Println() *Deque[T]

Println writes the elements of the Deque to the standard output (console) with a newline and returns the Deque unchanged.

func (*Deque[T]) PushBack added in v1.0.181

func (dq *Deque[T]) PushBack(value T)

PushBack adds an element to the back of the Deque.

func (*Deque[T]) PushFront added in v1.0.181

func (dq *Deque[T]) PushFront(value T)

PushFront adds an element to the front of the Deque.

func (*Deque[T]) Remove added in v1.0.181

func (dq *Deque[T]) Remove(index Int) Option[T]

Remove removes and returns the element at the specified index. Returns None if the index is out of bounds.

func (*Deque[T]) Reserve added in v1.0.181

func (dq *Deque[T]) Reserve(additional Int)

Reserve ensures that the Deque can hold at least the specified number of elements without reallocating. If the current capacity is already sufficient, this is a no-op.

func (*Deque[T]) Retain added in v1.0.181

func (dq *Deque[T]) Retain(predicate func(T) bool)

Retain keeps only the elements specified by the predicate.

func (*Deque[T]) RotateLeft added in v1.0.181

func (dq *Deque[T]) RotateLeft(mid Int)

RotateLeft rotates the Deque in-place such that the first mid elements move to the end while the last len - mid elements move to the front.

func (*Deque[T]) RotateRight added in v1.0.181

func (dq *Deque[T]) RotateRight(k Int)

RotateRight rotates the Deque in-place such that the first len - k elements move to the end while the last k elements move to the front.

func (*Deque[T]) Set added in v1.0.181

func (dq *Deque[T]) Set(index Int, value T) bool

Set sets the element at the specified index. Index 0 represents the front of the Deque. Returns true if the index is valid, false otherwise.

func (*Deque[T]) ShrinkToFit added in v1.0.181

func (dq *Deque[T]) ShrinkToFit()

ShrinkToFit shrinks the capacity of the Deque as much as possible.

func (Deque[T]) String added in v1.0.181

func (dq Deque[T]) String() string

String returns a string representation of the Deque.

func (*Deque[T]) Swap added in v1.0.181

func (dq *Deque[T]) Swap(i, j Int)

Swap swaps the elements at indices i and j. Panics if either index is out of bounds.

func (*Deque[T]) ToSlice added in v1.0.181

func (dq *Deque[T]) ToSlice() Slice[T]

ToSlice converts the Deque to a Slice, maintaining element order.

type Dir

type Dir struct {
	// contains filtered or unexported fields
}

Dir is a struct representing a directory path.

func NewDir

func NewDir(path String) *Dir

NewDir returns a new Dir instance with the given path.

func (*Dir) Chown

func (d *Dir) Chown(uid, gid int) Result[*Dir]

Chown changes the ownership of the directory to the specified UID and GID. It uses os.Chown to modify ownership and returns a Result[*Dir] indicating success or failure.

func (*Dir) Copy

func (d *Dir) Copy(dest String, followLinks ...bool) Result[*Dir]

Copy copies the contents of the current directory to the destination directory.

Parameters:

- dest (String): The destination directory where the contents of the current directory should be copied.

- followLinks (optional): A boolean indicating whether to follow symbolic links during the walk. If true, symbolic links are followed; otherwise, they are skipped.

Returns:

- Result[*Dir]: A Result type containing either a pointer to a new Dir instance representing the destination directory or an error.

Example usage:

sourceDir := g.NewDir("path/to/source")
destinationDirResult := sourceDir.Copy("path/to/destination")
if destinationDirResult.IsErr() {
	// Handle error
}
destinationDir := destinationDirResult.Ok()

func (*Dir) Create

func (d *Dir) Create(mode ...os.FileMode) Result[*Dir]

Create creates a new directory with the specified mode (optional).

Parameters:

- mode (os.FileMode, optional): The file mode for the new directory. If not provided, it defaults to DirDefault (0755).

Returns:

- *Dir: A pointer to the Dir instance on which the method was called.

Example usage:

dir := g.NewDir("path/to/directory")
createdDir := dir.Create(0755) // Optional mode argument

func (*Dir) CreateAll

func (d *Dir) CreateAll(mode ...os.FileMode) Result[*Dir]

CreateAll creates all directories along the given path, with the specified mode (optional).

Parameters:

- mode ...os.FileMode (optional): The file mode to be used when creating the directories. If not provided, it defaults to the value of DirDefault constant (0755).

Returns:

- *Dir: A pointer to the Dir instance representing the created directories.

Example usage:

dir := g.NewDir("path/to/directory")
dir.CreateAll()
dir.CreateAll(0755)

func (*Dir) CreateTemp

func (*Dir) CreateTemp(args ...String) Result[*Dir]

CreateTemp creates a new temporary directory in the specified directory with the specified name pattern and returns a Result, which contains a pointer to the Dir or an error if the operation fails. If no directory is specified, the default directory for temporary directories is used. If no name pattern is specified, the default pattern "*" is used.

Parameters:

- args ...String: A variadic parameter specifying the directory and/or name pattern for the temporary directory.

Returns:

- *Dir: A pointer to the Dir representing the temporary directory.

Example usage:

d := g.NewDir("") tmpdir := d.CreateTemp() // Creates a temporary directory with default settings tmpdirWithDir := d.CreateTemp("mydir") // Creates a temporary directory in "mydir" directory tmpdirWithPattern := d.CreateTemp("", "tmp") // Creates a temporary directory with "tmp" pattern

func (*Dir) Exist

func (d *Dir) Exist() bool

Exist checks if the current directory exists.

Returns:

- bool: true if the current directory exists, false otherwise.

Example usage:

dir := g.NewDir("path/to/directory")
exists := dir.Exist()

func (*Dir) Glob

func (d *Dir) Glob() SeqResult[*File]

Glob iterates over files in the current directory matching a specified pattern and yields File instances for each match. This method utilizes a lazy evaluation strategy, processing files as they are needed.

Returns:

  • SeqResult[*File]: A sequence of Result[*File] instances representing the files that match the provided pattern in the current directory. It returns an error if the glob operation fails.

Example usage:

dir := g.NewDir("path/to/directory/*.txt")
files := dir.Glob()
for file := range files {
    fmt.Println(file.Ok().Name())
}
func (d *Dir) IsLink() bool

IsLink checks if the directory is a symbolic link.

func (*Dir) Join

func (d *Dir) Join(elem ...String) Result[String]

Join joins the current directory path with the given path elements, returning the joined path.

Parameters:

- elem (...String): One or more String values representing path elements to be joined with the current directory path.

Returns:

- String: The resulting joined path as an String.

Example usage:

dir := g.NewDir("path/to/directory")
joinedPath := dir.Join("subdir", "file.txt")

func (*Dir) Lstat

func (d *Dir) Lstat() Result[fs.FileInfo]

Lstat retrieves information about the symbolic link represented by the Dir instance. It returns a Result[fs.FileInfo] containing details about the symbolic link's metadata. Unlike Stat, Lstat does not follow the link and provides information about the link itself.

func (*Dir) Move

func (d *Dir) Move(newpath String) Result[*Dir]

Move function simply calls Dir.Rename

func (*Dir) Path

func (d *Dir) Path() Result[String]

Path returns the absolute path of the current directory.

Returns:

- String: The absolute path of the current directory as an String. If an error occurs while converting the path to an absolute path, the error is stored in d.err, which can be checked using the Error() method.

Example usage:

dir := g.NewDir("path/to/directory")
absPath := dir.Path()

func (*Dir) Print

func (d *Dir) Print() *Dir

Print writes the content of the Dir to the standard output (console) and returns the Dir unchanged.

func (*Dir) Println added in v1.0.122

func (d *Dir) Println() *Dir

Println writes the content of the Dir to the standard output (console) with a newline and returns the Dir unchanged.

func (*Dir) Read

func (d *Dir) Read() SeqResult[*File]

Read iterates over the content of the current directory and yields File instances for each entry. This method uses a lazy evaluation strategy where each file is processed one at a time as it is needed.

Returns:

  • SeqResult[*File]: A sequence of Result[*File] instances representing each file and directory in the current directory. It returns an error if reading the directory fails.

Example usage:

dir := g.NewDir("path/to/directory")
files := dir.Read()
for file := range files {
    fmt.Println(file.Ok().Name())
}

func (*Dir) Remove

func (d *Dir) Remove() Result[*Dir]

Remove attempts to delete the directory and its contents. It returns a Result, which contains either the *Dir or an error. If the directory does not exist, Remove returns a successful Result with *Dir set. Any error that occurs during removal will be of type *PathError.

func (*Dir) Rename

func (d *Dir) Rename(newpath String) Result[*Dir]

Rename renames the current directory to the new path.

Parameters:

- newpath String: The new path for the directory.

Returns:

- *Dir: A pointer to the Dir instance representing the renamed directory. If an error occurs, the original Dir instance is returned with the error stored in d.err, which can be checked using the Error() method.

Example usage:

dir := g.NewDir("path/to/directory")
dir.Rename("path/to/new_directory")

func (*Dir) SetPath

func (d *Dir) SetPath(path String) *Dir

SetPath sets the path of the current directory.

Parameters:

- path (String): The new path to be set for the current directory.

Returns:

- *Dir: A pointer to the updated Dir instance with the new path.

Example usage:

dir := g.NewDir("path/to/directory")
dir.SetPath("new/path/to/directory")

func (*Dir) Stat

func (d *Dir) Stat() Result[fs.FileInfo]

Stat retrieves information about the directory represented by the Dir instance. It returns a Result[fs.FileInfo] containing details about the directory's metadata.

func (*Dir) String added in v1.0.86

func (d *Dir) String() String

String returns the String representation of the current directory's path.

func (*Dir) Temp

func (*Dir) Temp() *Dir

Temp returns the default directory to use for temporary files.

On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.

The directory is neither guaranteed to exist nor have accessible permissions.

func (*Dir) Walk

func (d *Dir) Walk() SeqResult[*File]

Walk returns a lazy sequence of all files and directories under the current Dir. You can customize inclusion/exclusion using SeqResult methods (Exclude, Filter, etc.).

Example usage:

NewDir("path/to/dir").
  Walk().
  Exclude((*File).IsLink).
  ForEach(func(r Result[*File]) {
      if r.IsOk() {
          fmt.Println(r.Ok().Path().Ok().Std())
      }
  })

type ErrFileClosed

type ErrFileClosed struct{ Msg string }

ErrFileClosed represents an error for when a file is already closed.

func (*ErrFileClosed) Error

func (e *ErrFileClosed) Error() string

Error returns the error message for ErrFileClosed.

type ErrFileNotExist

type ErrFileNotExist struct{ Msg string }

ErrFileNotExist represents an error for when a file does not exist.

func (*ErrFileNotExist) Error

func (e *ErrFileNotExist) Error() string

Error returns the error message for ErrFileNotExist.

type File

type File struct {
	// contains filtered or unexported fields
}

File is a struct that represents a file along with an iterator for reading lines.

func NewFile

func NewFile[T ~string](name T) *File

NewFile returns a new File instance with the given name.

func (*File) Append

func (f *File) Append(content String, mode ...os.FileMode) Result[*File]

Append appends the given content to the file, with the specified mode (optional). If no FileMode is provided, the default FileMode (0644) is used. Don't forget to close the file!

func (*File) Chmod

func (f *File) Chmod(mode os.FileMode) Result[*File]

Chmod changes the mode of the file.

func (*File) Chown

func (f *File) Chown(uid, gid int) Result[*File]

Chown changes the owner of the file.

func (*File) Chunks added in v1.0.57

func (f *File) Chunks(size Int) SeqResult[String]

Chunks returns a new iterator instance that can be used to read the file in fixed-size chunks of the specified size in bytes.

Parameters:

- size (int): The size of each chunk in bytes.

Example usage:

// Open a new file with the specified name "text.txt"
g.NewFile("text.txt").
	Chunks(100).              // Read the file in chunks of 100 bytes
	Map(g.String.Upper).      // Convert each chunk to uppercase
	ForEach(                  // For each line, print it
		func(func(s Result[String]) {
			s.Ok().Print()
		})

// Output:
// UPPERCASED_CHUNK1
// UPPERCASED_CHUNK2
// UPPERCASED_CHUNK3

func (*File) ChunksRaw added in v1.0.150

func (f *File) ChunksRaw(size Int) SeqResult[Bytes]

ChunksRaw returns a new iterator instance that reads the file in fixed-size chunks of bytes, yielding each chunk as a Bytes slice.

This method avoids intermediate string allocations and operates directly on byte slices. Each chunk is copied from the underlying buffer to make it safe for downstream use.

Parameters:

- size (Int): The size of each chunk in bytes. Must be > 0.

Returns:

- SeqResult[Bytes]: An iterator over raw byte chunks from the file.

Example usage:

g.NewFile("text.txt").
	ChunksRaw(128).            // Read raw 128-byte chunks
	ForEach(func(chunk g.Result[g.Bytes]) {
		chunk.Ok().Print()
	})

Output: RAW_CHUNK_1 RAW_CHUNK_2 ...

Note: Each chunk is copied from the buffer to ensure memory safety.

func (*File) Close

func (f *File) Close() error

Close closes the File and unlocks its underlying file, if it is not already closed.

func (*File) Copy

func (f *File) Copy(dest String, mode ...os.FileMode) Result[*File]

Copy copies the file to the specified destination, with the specified mode (optional). If no mode is provided, the default FileMode (0644) is used.

func (*File) Create

func (f *File) Create() Result[*File]

Create is similar to os.Create, but it returns a write-locked file. Don't forget to close the file!

func (*File) CreateTemp

func (f *File) CreateTemp(args ...String) Result[*File]

CreateTemp creates a new temporary file in the specified directory with the specified name pattern and returns a Result, which contains a pointer to the File or an error if the operation fails. If no directory is specified, the default directory for temporary files is used. If no name pattern is specified, the default pattern "*" is used.

Parameters:

- args ...String: A variadic parameter specifying the directory and/or name pattern for the temporary file.

Returns:

- *File: A pointer to the File representing the temporary file.

Example usage:

f := g.NewFile("")
tmpfile := f.CreateTemp()                     // Creates a temporary file with default settings
tmpfileWithDir := f.CreateTemp("mydir")       // Creates a temporary file in "mydir" directory
tmpfileWithPattern := f.CreateTemp("", "tmp") // Creates a temporary file with "tmp" pattern

func (*File) Decode added in v1.0.85

func (f *File) Decode() fdecode

Decode returns an fdecode struct wrapping the given file for decoding.

func (*File) Dir

func (f *File) Dir() Result[*Dir]

Dir returns the directory the file is in as an Dir instance.

func (*File) Encode added in v1.0.85

func (f *File) Encode() fencode

Encode returns an fencode struct wrapping the given file for encoding.

func (*File) Exist

func (f *File) Exist() bool

Exist checks if the file exists.

func (*File) Ext

func (f *File) Ext() String

Ext returns the file extension.

func (*File) Guard

func (f *File) Guard() *File

Guard sets a lock on the file to protect it from concurrent access. It returns the File instance with the guard enabled.

func (*File) IsDir

func (f *File) IsDir() bool

IsDir checks if the file is a directory.

func (f *File) IsLink() bool

IsLink checks if the file is a symbolic link.

func (*File) Lines

func (f *File) Lines() SeqResult[String]

Lines returns a new iterator instance that can be used to read the file line by line.

Example usage:

// Open a new file with the specified name "text.txt"
g.NewFile("text.txt").
	Lines().                 // Read the file line by line
	Skip(3).                 // Skip the first 3 lines
	Exclude(f.Zero).         // Exclude lines that are empty or contain only whitespaces
	Dedup().                 // Remove consecutive duplicate lines
	Map(g.String.Upper).     // Convert each line to uppercase
	ForEach(                 // For each line, print it
		func(func(s Result[String]) {
			s.Ok().Print()
		})

// Output:
// UPPERCASED_LINE4
// UPPERCASED_LINE5
// UPPERCASED_LINE6

func (*File) LinesRaw added in v1.0.150

func (f *File) LinesRaw() SeqResult[Bytes]

LinesRaw returns a new iterator instance that reads the file line by line, yielding each line as a Bytes slice (raw []byte).

This version avoids intermediate string allocations by working directly with byte slices. The returned Bytes are copies of the scanner buffer and are safe to retain.

Returns:

- SeqResult[Bytes]: An iterator over raw byte lines from the file.

Example usage:

g.NewFile("text.txt").
	LinesRaw().                // Read raw byte lines
	Filter(func(b g.Bytes) bool {
		return len(b) > 0
	}).
	ForEach(func(line g.Result[g.Bytes]) {
		line.Ok().Print()
	})

Output: LINE_1 LINE_2 ...

Note: Each line is copied before yielding to avoid scanner buffer reuse issues.

func (*File) Lstat

func (f *File) Lstat() Result[fs.FileInfo]

Lstat retrieves information about the symbolic link represented by the *File instance. It returns a Result[fs.FileInfo] containing details about the symbolic link's metadata. Unlike Stat, Lstat does not follow the link and provides information about the link itself.

func (*File) MimeType

func (f *File) MimeType() Result[String]

MimeType returns the MIME type of the file as Result[String].

func (*File) Move

func (f *File) Move(newpath String) Result[*File]

Move function simply calls File.Rename

func (*File) Name

func (f *File) Name() String

Name returns the name of the file.

func (*File) Open

func (f *File) Open() Result[*File]

Open is like os.Open, but returns a read-locked file. Don't forget to close the file!

func (*File) OpenFile

func (f *File) OpenFile(flag int, perm fs.FileMode) Result[*File]

OpenFile is like os.OpenFile, but returns a locked file. If flag includes os.O_WRONLY or os.O_RDWR, the file is write-locked otherwise, it is read-locked. Don't forget to close the file!

func (*File) Path

func (f *File) Path() Result[String]

Path returns the absolute path of the file.

func (*File) Print

func (f *File) Print() *File

Print writes the content of the File to the standard output (console) and returns the File unchanged.

func (*File) Println added in v1.0.122

func (f *File) Println() *File

Println writes the content of the File to the standard output (console) with a newline and returns the File unchanged.

func (*File) Read

func (f *File) Read() Result[String]

Read opens the named file with a read-lock and returns its contents.

func (*File) Remove

func (f *File) Remove() Result[*File]

Remove removes the file.

func (*File) Rename

func (f *File) Rename(newpath String) Result[*File]

Rename renames the file to the specified new path.

func (*File) Seek

func (f *File) Seek(offset int64, whence int) Result[*File]

Seek sets the file offset for the next Read or Write operation. The offset is specified by the 'offset' parameter, and the 'whence' parameter determines the reference point for the offset.

The 'offset' parameter specifies the new offset in bytes relative to the reference point determined by 'whence'. If 'whence' is set to io.SeekStart, io.SeekCurrent, or io.SeekEnd, the offset is relative to the start of the file, the current offset, or the end of the file, respectively.

If the file is not open, this method will attempt to open it. If the open operation fails, an error is returned.

If the Seek operation fails, the file is closed, and an error is returned.

Example:

file := g.NewFile("example.txt")
result := file.Seek(100, io.SeekStart)
if result.Err() != nil {
    log.Fatal(result.Err())
}

Parameters:

  • offset: The new offset in bytes.
  • whence: The reference point for the offset (io.SeekStart, io.SeekCurrent, or io.SeekEnd).

Don't forget to close the file!

func (*File) Split

func (f *File) Split() (*Dir, *File)

Split splits the file path into its directory and file components.

func (*File) Stat

func (f *File) Stat() Result[fs.FileInfo]

Stat returns the fs.FileInfo of the file. It calls the file's Stat method if the file is open, or os.Stat otherwise.

func (*File) Std

func (f *File) Std() *os.File

Std returns the underlying *os.File instance. Don't forget to close the file with g.File().Close()!

func (*File) Write

func (f *File) Write(content String, mode ...os.FileMode) Result[*File]

Write opens the named file (creating it with the given permissions if needed), then write-locks it and overwrites it with the given content.

func (*File) WriteFromReader

func (f *File) WriteFromReader(scr io.Reader, mode ...os.FileMode) Result[*File]

WriteFromReader takes an io.Reader (scr) as input and writes the data from the reader into the file. If no FileMode is provided, the default FileMode (0644) is used.

type Float

type Float float64

Float is an alias for the float64 type.

func NewFloat

func NewFloat[T constraints.Float | constraints.Integer](float T) Float

NewFloat creates a new Float with the provided value.

func (Float) Abs

func (f Float) Abs() Float

Abs returns the absolute value of the Float.

func (Float) Add

func (f Float) Add(b Float) Float

Add adds two Floats and returns the result.

func (Float) BigFloat added in v1.0.81

func (f Float) BigFloat() *big.Float

BigFloat returns the Float as a *big.Float.

func (Float) Bits added in v1.0.179

func (f Float) Bits() uint64

Bits returns IEEE-754 representation of f.

func (Float) BytesBE added in v1.0.180

func (f Float) BytesBE() Bytes

BytesBE returns the IEEE-754 representation of the Float as Bytes in BigEndian order. The Float is converted to its 64-bit IEEE-754 binary representation.

func (Float) BytesLE added in v1.0.180

func (f Float) BytesLE() Bytes

BytesLE returns the IEEE-754 representation of the Float as Bytes in LittleEndian order. The Float is converted to its 64-bit IEEE-754 binary representation.

func (Float) CeilDecimal added in v1.0.194

func (f Float) CeilDecimal(precision Int) Float

CeilDecimal rounds the Float value up (towards +Inf) to the specified number of decimal places.

Parameters:

  • precision (Int): The number of decimal places to round up to. If negative, the Float is returned unchanged. Values greater than 308 are capped at 308.

Returns:

  • Float: A new Float value rounded up to the specified number of decimal places.

func (Float) Cmp added in v1.0.70

func (f Float) Cmp(b Float) cmp.Ordering

Cmp compares two Floats and returns an cmp.Ordering.

func (Float) Div

func (f Float) Div(b Float) Float

Div divides two Floats and returns the result.

func (Float) Eq

func (f Float) Eq(b Float) bool

Eq checks if two Floats are equal.

func (Float) Float32 added in v1.0.81

func (f Float) Float32() float32

Float32 returns the Float as a float32.

func (Float) FloorDecimal added in v1.0.194

func (f Float) FloorDecimal(precision Int) Float

FloorDecimal rounds the Float value down (towards -Inf) to the specified number of decimal places.

Parameters:

  • precision (Int): The number of decimal places to round down to. If negative, the Float is returned unchanged. Values greater than 308 are capped at 308.

Returns:

  • Float: A new Float value rounded down to the specified number of decimal places.

func (Float) Gt

func (f Float) Gt(b Float) bool

Gt checks if the Float is greater than the specified Float.

func (Float) Int added in v1.0.81

func (f Float) Int() Int

Int returns the Float as an Int.

func (Float) IsZero

func (f Float) IsZero() bool

IsZero checks if the Float is 0.

func (Float) Lt

func (f Float) Lt(b Float) bool

Lt checks if the Float is less than the specified Float.

func (Float) Max

func (f Float) Max(b ...Float) Float

Max returns the maximum of two Floats.

func (Float) Min

func (f Float) Min(b ...Float) Float

Min returns the minimum of two Floats.

func (Float) Mod added in v1.0.194

func (f Float) Mod(b Float) Float

Mod returns the floating-point remainder of f / b as defined by IEEE 754.

Parameters:

  • b (Float): The divisor.

Returns:

  • Float: The remainder of f / b.

Example usage:

f := g.NewFloat(5.5)
result := f.Mod(2) // result = 1.5

func (Float) Mul

func (f Float) Mul(b Float) Float

Mul multiplies two Floats and returns the result.

func (Float) Ne

func (f Float) Ne(b Float) bool

Ne checks if two Floats are not equal.

func (Float) Pow added in v1.0.194

func (f Float) Pow(exp Float) Float

Pow raises the Float to the power of the given exponent.

Parameters:

  • exp (Float): The exponent to raise the Float to.

Returns:

  • Float: The result of raising the Float to the specified power.

Example usage:

f := g.NewFloat(2)
result := f.Pow(3) // result = 8

func (Float) Print

func (f Float) Print() Float

Print writes the value of the Float to the standard output (console) and returns the Float unchanged.

func (Float) Println added in v1.0.122

func (f Float) Println() Float

Println writes the value of the Float to the standard output (console) with a newline and returns the Float unchanged.

func (Float) Round

func (f Float) Round() Int

Round rounds the Float to the nearest integer and returns the result as an Int.

func (Float) RoundDecimal

func (f Float) RoundDecimal(precision Int) Float

RoundDecimal rounds the Float value to the specified number of decimal places.

Parameters:

  • precision (Int): The number of decimal places to round to. If negative, the Float is returned unchanged. Values greater than 308 are capped at 308 to prevent overflow.

Returns:

  • Float: A new Float value rounded to the specified number of decimal places.

func (Float) Sqrt added in v1.0.194

func (f Float) Sqrt() Float

Sqrt returns the square root of the Float.

Returns:

  • Float: The square root of the Float. If the Float is negative, the result is NaN.

Example usage:

f := g.NewFloat(9)
result := f.Sqrt() // result = 3

func (Float) Std

func (f Float) Std() float64

Std returns the Float as a float64.

func (Float) String added in v1.0.81

func (f Float) String() String

String returns the Float as an String.

func (Float) Sub

func (f Float) Sub(b Float) Float

Sub subtracts two Floats and returns the result.

func (Float) Transform added in v1.0.89

func (f Float) Transform(fn func(Float) Float) Float

Transform applies a transformation function to the Float and returns the result.

func (Float) TruncDecimal added in v1.0.194

func (f Float) TruncDecimal(precision Int) Float

TruncDecimal truncates the Float value to the specified number of decimal places.

Parameters:

  • precision (Int): The number of decimal places to truncate to. If negative, the Float is returned unchanged. Values greater than 308 are capped at 308.

Returns:

  • Float: A new Float value truncated to the specified number of decimal places.

type Heap added in v1.0.181

type Heap[T any] struct {
	// contains filtered or unexported fields
}

Heap is a generic binary heap data structure that maintains elements in heap order. It can be configured as either a min-heap or max-heap based on the comparison function.

func NewHeap added in v1.0.181

func NewHeap[T any](compareFn func(T, T) cmp.Ordering) *Heap[T]

NewHeap creates a new heap with the given comparison function. The comparison function should return: - cmp.Less if the first argument should have higher priority - cmp.Greater if the second argument should have higher priority - cmp.Equal if they have equal priority

func (*Heap[T]) Clear added in v1.0.181

func (h *Heap[T]) Clear()

Clear removes all elements from the heap.

func (*Heap[T]) Clone added in v1.0.181

func (h *Heap[T]) Clone() *Heap[T]

Clone creates a deep copy of the heap.

func (*Heap[T]) Empty added in v1.0.181

func (h *Heap[T]) Empty() bool

Empty returns true if the heap contains no elements.

func (*Heap[T]) IntoIter added in v1.0.181

func (h *Heap[T]) IntoIter() SeqHeap[T]

IntoIter returns a consuming iterator that yields elements in sorted order.

This iterator consumes the original heap by repeatedly calling Pop() until the heap is empty. After iteration completes (or is stopped early), the original heap will be empty. Elements are yielded in the order determined by the heap's comparison function (smallest first for min-heap, largest first for max-heap).

Use this method when you want to consume the heap and don't need the original data structure afterwards, or when you want to transfer ownership of the elements.

Time complexity: O(n log n) for full iteration Space complexity: O(1) - no additional memory allocation

Returns:

- SeqSlice[T]: An iterator that yields elements in sorted order while consuming the heap

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(10, 5, 15, 1, 8)

// Consume the heap while iterating
result := heap.IntoIter().Collect() // [1, 5, 8, 10, 15]

fmt.Printf("Heap now has %d elements\n", heap.Len()) // Output: 0

// Can be stopped early, leaving remaining elements in heap
heap2 := g.NewHeap(cmp.Cmp[int])
heap2.Push(20, 25, 15, 30)

heap2.IntoIter().Take(2).ForEach(func(x int) {
	fmt.Printf("%d ", x) // Output: 15 20
})
fmt.Printf("Remaining: %d elements\n", heap2.Len()) // Output: 2

func (*Heap[T]) Iter added in v1.0.181

func (h *Heap[T]) Iter() SeqHeap[T]

Iter returns a non-consuming iterator that yields elements in sorted order.

The iterator creates a clone of the heap and yields elements by repeatedly calling Pop() on the clone, ensuring the original heap remains unchanged. Elements are yielded in the order determined by the heap's comparison function (smallest first for min-heap, largest first for max-heap).

Time complexity: O(n log n) for full iteration Space complexity: O(n) for the heap clone

Returns:

- SeqSlice[T]: An iterator that yields elements in sorted order

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(10, 5, 15, 1, 8)

// Iterate without consuming the original heap
heap.Iter().ForEach(func(x int) {
	fmt.Printf("%d ", x) // Output: 1 5 8 10 15
})

fmt.Printf("Heap still has %d elements\n", heap.Len()) // Output: 5

// Can be used with other iterator methods
firstThree := heap.Iter().Take(3).Collect() // [1, 5, 8]
evenNumbers := heap.Iter().Filter(func(x int) bool {
	return x%2 == 0
}).Collect() // [8, 10]

func (*Heap[T]) Len added in v1.0.181

func (h *Heap[T]) Len() Int

Len returns the number of elements in the heap.

func (*Heap[T]) Peek added in v1.0.181

func (h *Heap[T]) Peek() Option[T]

Peek returns the top element without removing it. Returns None if the heap is empty.

func (*Heap[T]) Pop added in v1.0.181

func (h *Heap[T]) Pop() Option[T]

Pop removes and returns the top element from the heap. Returns None if the heap is empty.

func (*Heap[T]) Print added in v1.0.181

func (h *Heap[T]) Print() *Heap[T]

Print writes the elements of the Heap to the standard output (console) and returns the Heap unchanged.

func (*Heap[T]) Println added in v1.0.181

func (h *Heap[T]) Println() *Heap[T]

Println writes the elements of the Heap to the standard output (console) with a newline and returns the Heap unchanged.

func (*Heap[T]) Push added in v1.0.181

func (h *Heap[T]) Push(items ...T)

Push adds one or more items to the heap.

func (Heap[T]) String added in v1.0.181

func (h Heap[T]) String() string

String returns a string representation of the heap.

func (*Heap[T]) ToSlice added in v1.0.181

func (h *Heap[T]) ToSlice() Slice[T]

ToSlice returns a slice containing all elements in the heap. The order is not guaranteed to be sorted.

func (*Heap[T]) Transform added in v1.0.181

func (h *Heap[T]) Transform(fn func(*Heap[T]) *Heap[T]) *Heap[T]

Transform applies a transformation function to the Heap and returns the result.

type Int

type Int int

Int is an alias for the int type.

func NewInt

func NewInt[T constraints.Integer | rune | byte](i T) Int

NewInt creates a new Int with the provided int value.

func (Int) Abs

func (i Int) Abs() Int

Abs returns the absolute value of the Int.

func (Int) Add

func (i Int) Add(b Int) Int

Add adds two Ints and returns the result.

func (Int) BigInt added in v1.0.81

func (i Int) BigInt() *big.Int

BigInt returns the Int as a *big.Int.

func (Int) Binary added in v1.0.81

func (i Int) Binary() String

Binary returns the Int as a binary string.

func (Int) BytesBE added in v1.0.180

func (i Int) BytesBE() Bytes

BytesBE converts the Int to Bytes in BigEndian order. Leading zero bytes are removed while preserving the sign bit for negative numbers.

func (Int) BytesLE added in v1.0.180

func (i Int) BytesLE() Bytes

BytesLE converts the Int to Bytes in LittleEndian order. Trailing zero bytes are removed while preserving the sign bit for negative numbers

func (Int) Cmp added in v1.0.70

func (i Int) Cmp(b Int) cmp.Ordering

Cmp compares two Ints and returns an cmp.Ordering.

func (Int) Div

func (i Int) Div(b Int) Int

Div divides two Ints and returns the result.

func (Int) Eq

func (i Int) Eq(b Int) bool

Eq checks if two Ints are equal.

func (Int) Float added in v1.0.81

func (i Int) Float() Float

Float returns the Int as an Float.

func (Int) Gt

func (i Int) Gt(b Int) bool

Gt checks if the Int is greater than the specified Int.

func (Int) Gte

func (i Int) Gte(b Int) bool

Gte checks if the Int is greater than or equal to the specified Int.

func (Int) Hex added in v1.0.81

func (i Int) Hex() String

Hex returns the Int as a hexadecimal string.

func (Int) Int16 added in v1.0.81

func (i Int) Int16() int16

Int16 returns the Int as an int16.

func (Int) Int32 added in v1.0.81

func (i Int) Int32() int32

Int32 returns the Int as an int32.

func (Int) Int64 added in v1.0.81

func (i Int) Int64() int64

Int64 returns the Int as an int64.

func (Int) Int8 added in v1.0.81

func (i Int) Int8() int8

Int8 returns the Int as an int8.

func (Int) IsNegative

func (i Int) IsNegative() bool

IsNegative checks if the Int is negative.

func (Int) IsPositive

func (i Int) IsPositive() bool

IsPositive checks if the Int is positive.

func (Int) IsZero

func (i Int) IsZero() bool

IsZero checks if the Int is 0.

func (Int) Lt

func (i Int) Lt(b Int) bool

Lt checks if the Int is less than the specified Int.

func (Int) Lte

func (i Int) Lte(b Int) bool

Lte checks if the Int is less than or equal to the specified Int.

func (Int) Max

func (i Int) Max(b ...Int) Int

Max returns the maximum of Ints.

func (Int) Min

func (i Int) Min(b ...Int) Int

Min returns the minimum of Ints.

func (Int) Mul

func (i Int) Mul(b Int) Int

Mul multiplies two Ints and returns the result.

func (Int) Ne

func (i Int) Ne(b Int) bool

Ne checks if two Ints are not equal.

func (Int) Octal added in v1.0.81

func (i Int) Octal() String

Octal returns the Int as an octal string.

func (Int) Print

func (i Int) Print() Int

Print writes the value of the Int to the standard output (console) and returns the Int unchanged.

func (Int) Println added in v1.0.122

func (i Int) Println() Int

Println writes the value of the Int to the standard output (console) with a newline and returns the Int unchanged.

func (Int) Random

func (i Int) Random() Int

Random returns a random Int in the range [0, hi].

func (Int) RandomRange

func (i Int) RandomRange(to Int) Int

RandomRange returns a random Int in the inclusive range [i, to]. The order of bounds does not matter (it normalizes to [min, max]). Works for negative bounds and the full int64 range without overflow or bias.

func (Int) Rem

func (i Int) Rem(b Int) Int

Rem returns the remainder of the division between the receiver and the input value.

func (Int) Std

func (i Int) Std() int

Std returns the Int as an int.

func (Int) String added in v1.0.81

func (i Int) String() String

String returns the Int as an String.

func (Int) Sub

func (i Int) Sub(b Int) Int

Sub subtracts two Ints and returns the result.

func (Int) Transform added in v1.0.89

func (i Int) Transform(fn func(Int) Int) Int

Transform applies a transformation function to the Int and returns the result.

func (Int) UInt added in v1.0.81

func (i Int) UInt() uint

UInt returns the Int as a uint.

func (Int) UInt16 added in v1.0.81

func (i Int) UInt16() uint16

UInt16 returns the Int as a uint16.

func (Int) UInt32 added in v1.0.81

func (i Int) UInt32() uint32

UInt32 returns the Int as a uint32.

func (Int) UInt64 added in v1.0.81

func (i Int) UInt64() uint64

UInt64 returns the Int as a uint64.

func (Int) UInt8 added in v1.0.81

func (i Int) UInt8() uint8

UInt8 returns the Int as a uint8.

type Map

type Map[K comparable, V any] map[K]V

Map is a generic alias for a map.

func NewMap

func NewMap[K comparable, V any](size ...Int) Map[K, V]

NewMap creates a new Map of the specified size or an empty Map if no size is provided.

func (Map[K, V]) Clear

func (m Map[K, V]) Clear()

Clear removes all key-value pairs from the Map.

func (Map[K, V]) Clone

func (m Map[K, V]) Clone() Map[K, V]

Clone creates a new Map that is a copy of the original Map.

func (Map[K, V]) Contains

func (m Map[K, V]) Contains(key K) bool

Contains checks if the Map contains the specified key.

func (Map[K, V]) Copy

func (m Map[K, V]) Copy(src Map[K, V])

Copy copies the source Map's key-value pairs to the target Map.

func (Map[K, V]) Delete

func (m Map[K, V]) Delete(keys ...K)

Delete removes the specified keys from the Map.

func (Map[K, V]) Empty

func (m Map[K, V]) Empty() bool

Empty checks if the Map is empty.

func (Map[K, V]) Entry added in v1.0.153

func (m Map[K, V]) Entry(key K) MapEntry[K, V]

Entry returns an MapEntry object for the given key, providing fine‑grained control over insertion and modification of its value.

Example:

m := g.NewMap[string, int]()
// Insert 1 if "foo" is absent, then increment it
e := m.Entry("foo")
e.OrSet(1)
e.Transform(func(v int) int { return v + 1 })

The entire operation requires only a single key lookup and works without additional allocations.

func (Map[K, V]) Eq

func (m Map[K, V]) Eq(other Map[K, V]) bool

Eq checks if two Maps are equal.

func (Map[K, V]) Get

func (m Map[K, V]) Get(k K) Option[V]

Get retrieves the value associated with the given key.

func (Map[K, V]) Invert

func (m Map[K, V]) Invert() Map[any, K]

Invert inverts the keys and values of the Map, returning a new Map with values as keys and keys as values. Note that the inverted Map will have 'any' as the key type, since not all value types are guaranteed to be comparable.

func (Map[K, V]) Iter

func (m Map[K, V]) Iter() SeqMap[K, V]

Iter returns an iterator (SeqMap[K, V]) for the Map, allowing for sequential iteration over its key-value pairs. It is commonly used in combination with higher-order functions, such as 'ForEach', to perform operations on each key-value pair of the Map.

Returns:

- SeqMap[K, V], which can be used for sequential iteration over the key-value pairs of the Map.

Example usage:

myMap := g.Map[string, int]{"one": 1, "two": 2, "three": 3}
iterator := myMap.Iter()
iterator.ForEach(func(key string, value int) {
	// Perform some operation on each key-value pair
	fmt.Printf("%s: %d\n", key, value)
})

The 'Iter' method provides a convenient way to traverse the key-value pairs of a Map in a functional style, enabling operations like mapping or filtering.

func (Map[K, V]) Keys

func (m Map[K, V]) Keys() Slice[K]

Keys returns a slice of the Map's keys.

func (Map[K, V]) Len

func (m Map[K, V]) Len() Int

Len returns the number of key-value pairs in the Map.

func (Map[K, V]) Ne

func (m Map[K, V]) Ne(other Map[K, V]) bool

Ne checks if two Maps are not equal.

func (Map[K, V]) NotEmpty

func (m Map[K, V]) NotEmpty() bool

NotEmpty checks if the Map is not empty.

func (Map[K, V]) Print

func (m Map[K, V]) Print() Map[K, V]

Print writes the key-value pairs of the Map to the standard output (console) and returns the Map unchanged.

func (Map[K, V]) Println added in v1.0.122

func (m Map[K, V]) Println() Map[K, V]

Println writes the key-value pairs of the Map to the standard output (console) with a newline and returns the Map unchanged.

func (Map[K, V]) Set

func (m Map[K, V]) Set(key K, value V) Option[V]

Set sets the value for the key and returns the previous value if it existed.

func (Map[K, V]) Std

func (m Map[K, V]) Std() map[K]V

Std converts the Map to a regular Go map.

func (Map[K, V]) String

func (m Map[K, V]) String() string

String returns a string representation of the Map.

func (Map[K, V]) ToMapOrd added in v1.0.114

func (m Map[K, V]) ToMapOrd() MapOrd[K, V]

ToMapOrd converts a standard Map to an ordered Map.

func (Map[K, V]) ToMapSafe added in v1.0.114

func (m Map[K, V]) ToMapSafe() *MapSafe[K, V]

ToMapSafe converts a standard Map to a thread-safe Map.

func (Map[K, V]) Transform added in v1.0.89

func (m Map[K, V]) Transform(fn func(Map[K, V]) Map[K, V]) Map[K, V]

Transform applies a transformation function to the Map and returns the result.

func (Map[K, V]) Values

func (m Map[K, V]) Values() Slice[V]

Values returns a slice of the Map's values.

type MapEntry added in v1.0.153

type MapEntry[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapEntry provides a view into a single key of a Map. It exposes a fluent, chain-friendly interface for inspecting, inserting, mutating, or deleting a value with a single key lookup.

func (MapEntry[K, V]) Delete added in v1.0.153

func (e MapEntry[K, V]) Delete() Option[V]

Delete removes the key from the map. Returns Some(removed_value) if present, None otherwise.

func (MapEntry[K, V]) Get added in v1.0.153

func (e MapEntry[K, V]) Get() Option[V]

Get returns Some(value) if the key exists, otherwise None.

func (MapEntry[K, V]) OrDefault added in v1.0.153

func (e MapEntry[K, V]) OrDefault() Option[V]

OrDefault inserts the zero value if the key is vacant. Returns Some(existing) or None.

func (MapEntry[K, V]) OrSet added in v1.0.153

func (e MapEntry[K, V]) OrSet(value V) Option[V]

OrSet inserts value if the key is vacant. Returns Some(existing) or None if newly inserted.

func (MapEntry[K, V]) OrSetBy added in v1.0.153

func (e MapEntry[K, V]) OrSetBy(fn func() V) Option[V]

OrSetBy inserts the value from fn() if the key is vacant. Returns Some(existing) or None.

func (MapEntry[K, V]) Set added in v1.0.153

func (e MapEntry[K, V]) Set(value V) Option[V]

Set sets the value and returns Some(previous) if the key existed, or None otherwise.

func (MapEntry[K, V]) Transform added in v1.0.155

func (e MapEntry[K, V]) Transform(fn func(V) V) Option[V]

Transform applies fn to the existing value. Returns Some(updated) or None if key was absent.

type MapOrd

type MapOrd[K comparable, V any] []Pair[K, V] // ordered key-value pairs

MapOrd is an ordered map that maintains insertion order using a slice for pairs and a map for fast index lookups.

func MapOrdFromStd

func MapOrdFromStd[K comparable, V any](m map[K]V) MapOrd[K, V]

MapOrdFromStd converts a standard Go map to an ordered Map. The resulting ordered Map will maintain the order of its key-value pairs based on the order of insertion. This function is useful when you want to create an ordered Map from an existing Go map.

Parameters:

- m map[K]V: The input Go map to be converted to an ordered Map.

Returns:

- MapOrd[K, V]: New ordered Map containing the same key-value pairs as the input Go map.

Example usage:

mapOrd := g.MapOrdFromStd[string, int](goMap)

Converts the standard Go map 'map[K]V' to an ordered Map.

func NewMapOrd

func NewMapOrd[K comparable, V any](size ...Int) MapOrd[K, V]

NewMapOrd creates a new ordered Map with the specified size (if provided). An ordered Map is an Map that maintains the order of its key-value pairs based on the insertion order. If no size is provided, the default size will be used.

Parameters:

- size ...int: (Optional) The initial size of the ordered Map. If not provided, a default size will be used.

Returns:

- MapOrd[K, V]: Ordered Map with the specified initial size (or default size if not provided).

Example usage:

mapOrd := g.NewMapOrd[string, int](10)

Creates a new ordered Map with an initial size of 10.

func (*MapOrd[K, V]) Clear

func (mo *MapOrd[K, V]) Clear()

Clear removes all key-value pairs from the ordered Map.

func (MapOrd[K, V]) Clone

func (mo MapOrd[K, V]) Clone() MapOrd[K, V]

Clone creates a new ordered Map with the same key-value pairs.

func (MapOrd[K, V]) Contains

func (mo MapOrd[K, V]) Contains(key K) bool

Contains checks if the ordered Map contains the specified key.

func (*MapOrd[K, V]) Copy

func (mo *MapOrd[K, V]) Copy(src MapOrd[K, V])

Copy copies key-value pairs from the source ordered Map to the current ordered Map.

func (*MapOrd[K, V]) Delete

func (mo *MapOrd[K, V]) Delete(keys ...K)

Delete removes the specified keys from the ordered Map.

It preserves the original insertion order of the remaining elements and performs the deletion in a single pass with O(n) complexity.

Internally, it builds a set of keys to delete and reconstructs the map without the removed entries. Key lookup is optimized via a map[K]int index.

Example:

mo.Delete("a", "b", "c")

func (MapOrd[K, V]) Empty

func (mo MapOrd[K, V]) Empty() bool

Empty checks if the ordered Map is empty.

func (*MapOrd[K, V]) Entry added in v1.0.153

func (mo *MapOrd[K, V]) Entry(key K) MapOrdEntry[K, V]

Entry returns a MapOrdEntry object for the given key, providing fine-grained control over insertion, mutation, and deletion of its value in the ordered Map, while preserving the insertion order.

Example:

mo := g.NewMapOrd[string, int]()
// Insert 1 if "foo" is absent, then increment it
e := mo.Entry("foo")
e.OrSet(1).
e.Transform(func(v int) int { return v + 1 })

The entire operation requires only a single key lookup and works without additional allocations.

func (MapOrd[K, V]) Eq

func (mo MapOrd[K, V]) Eq(other MapOrd[K, V]) bool

Eq compares the current ordered Map to another ordered Map and returns true if they are equal.

func (MapOrd[K, V]) Get

func (mo MapOrd[K, V]) Get(key K) Option[V]

Get returns the value associated with the given key, wrapped in Option[V].

It returns Some(value) if the key exists, or None if it does not.

func (MapOrd[K, V]) Invert

func (mo MapOrd[K, V]) Invert() MapOrd[any, K]

Invert inverts the key-value pairs in the ordered Map, creating a new ordered Map with the values as keys and the original keys as values.

func (MapOrd[K, V]) IsSortedBy added in v1.0.193

func (mo MapOrd[K, V]) IsSortedBy(fn func(a, b Pair[K, V]) cmp.Ordering) bool

IsSortedBy checks if the ordered Map is sorted according to a custom comparison function.

Parameters:

- fn func(a, b Pair[K, V]) cmp.Ordering: The custom comparison function used for checking sort order.

Returns:

- bool: true if the map is sorted according to the comparison function, false otherwise.

Example usage:

sorted := hmapo.IsSortedBy(func(a, b g.Pair[g.String, g.Int]) cmp.Ordering { return a.Key.Cmp(b.Key) })

func (MapOrd[K, V]) IsSortedByKey added in v1.0.193

func (mo MapOrd[K, V]) IsSortedByKey(fn func(a, b K) cmp.Ordering) bool

IsSortedByKey checks if the ordered MapOrd[K, V] is sorted by the keys using a custom comparison function.

Parameters:

- fn func(a, b K) cmp.Ordering: The custom comparison function used for checking key sort order.

Returns:

- bool: true if the map is sorted by keys according to the comparison function, false otherwise.

Example usage:

sorted := hmapo.IsSortedByKey(func(a, b g.String) cmp.Ordering { return a.Cmp(b) })

func (MapOrd[K, V]) IsSortedByValue added in v1.0.193

func (mo MapOrd[K, V]) IsSortedByValue(fn func(a, b V) cmp.Ordering) bool

IsSortedByValue checks if the ordered MapOrd[K, V] is sorted by the values using a custom comparison function.

Parameters:

- fn func(a, b V) cmp.Ordering: The custom comparison function used for checking value sort order.

Returns:

- bool: true if the map is sorted by values according to the comparison function, false otherwise.

Example usage:

sorted := hmapo.IsSortedByValue(func(a, b g.Int) cmp.Ordering { return a.Cmp(b) })

func (MapOrd[K, V]) Iter

func (mo MapOrd[K, V]) Iter() SeqMapOrd[K, V]

Iter returns an iterator (SeqMapOrd[K, V]) for the ordered Map, allowing for sequential iteration over its key-value pairs. It is commonly used in combination with higher-order functions, such as 'ForEach', to perform operations on each key-value pair of the ordered Map.

Returns:

A SeqMapOrd[K, V], which can be used for sequential iteration over the key-value pairs of the ordered Map.

Example usage:

m := g.NewMapOrd[int, int]()
m.Set(1, 1)
m.Set(2, 2)
m.Set(3, 3).

m.Iter().ForEach(func(k, v int) {
    // Process key-value pair
})

The 'Iter' method provides a convenient way to traverse the key-value pairs of an ordered Map in a functional style, enabling operations like mapping or filtering.

func (MapOrd[K, V]) IterReverse added in v1.0.96

func (mo MapOrd[K, V]) IterReverse() SeqMapOrd[K, V]

IterReverse returns an iterator (SeqMapOrd[K, V]) for the ordered Map that allows for sequential iteration over its key-value pairs in reverse order. This method is useful when you need to process the elements from the last to the first.

Returns:

A SeqMapOrd[K, V], which can be used for sequential iteration over the key-value pairs of the ordered Map in reverse order.

Example usage:

m := g.NewMapOrd[int, int]()
m.Set(1, 1)
m.Set(2, 2)
m.Set(3, 3)

m.IterReverse().ForEach(func(k, v int) {
    // Process key-value pair in reverse order
    fmt.Println("Key:", k, "Value:", v)
})

The 'IterReverse' method complements the 'Iter' method by providing a way to access the elements in a reverse sequence, offering additional flexibility in data processing scenarios.

func (MapOrd[K, V]) Keys

func (mo MapOrd[K, V]) Keys() Slice[K]

Keys returns an Slice containing all the keys in the ordered Map.

func (MapOrd[K, V]) Len

func (mo MapOrd[K, V]) Len() Int

Len returns the number of key-value pairs in the ordered Map.

func (MapOrd[K, V]) Ne

func (mo MapOrd[K, V]) Ne(other MapOrd[K, V]) bool

Ne compares the current ordered Map to another ordered Map and returns true if they are not equal.

func (MapOrd[K, V]) NotEmpty

func (mo MapOrd[K, V]) NotEmpty() bool

NotEmpty checks if the ordered Map is not empty.

func (MapOrd[K, V]) Print

func (mo MapOrd[K, V]) Print() MapOrd[K, V]

Print writes the key-value pairs of the MapOrd to the standard output (console) and returns the MapOrd unchanged.

func (MapOrd[K, V]) Println added in v1.0.122

func (mo MapOrd[K, V]) Println() MapOrd[K, V]

Println writes the key-value pairs of the MapOrd to the standard output (console) with a newline and returns the MapOrd unchanged.

func (*MapOrd[K, V]) Set

func (mo *MapOrd[K, V]) Set(key K, value V) Option[V]

Set sets the value for the specified key in the ordered Map, and returns the previous value if it existed.

func (MapOrd[K, V]) Shuffle added in v1.0.88

func (mo MapOrd[K, V]) Shuffle()

Shuffle randomly reorders the elements of the ordered Map. It operates in place and affects the original order of the map's entries.

The function uses the crypto/rand package to generate random indices.

func (MapOrd[K, V]) SortBy

func (mo MapOrd[K, V]) SortBy(fn func(a, b Pair[K, V]) cmp.Ordering)

SortBy sorts the ordered Map by a custom comparison function.

Parameters:

- fn func(a, b Pair[K, V]) cmp.Ordering: The custom comparison function used for sorting the ordered Map.

Example usage:

hmapo.SortBy(func(a, b g.Pair[g.String, g.Int]) cmp.Ordering { return a.Key.Cmp(b.Key) })
hmapo.SortBy(func(a, b g.Pair[g.String, g.Int]) cmp.Ordering { return a.Value.Cmp(b.Value) })

func (MapOrd[K, V]) SortByKey added in v1.0.73

func (mo MapOrd[K, V]) SortByKey(fn func(a, b K) cmp.Ordering)

SortByKey sorts the ordered MapOrd[K, V] by the keys using a custom comparison function.

Parameters:

- fn func(a, b K) cmp.Ordering: The custom comparison function used for sorting the keys.

Example usage:

hmapo.SortByKey(func(a, b g.String) cmp.Ordering { return a.Cmp(b) })

func (MapOrd[K, V]) SortByValue added in v1.0.73

func (mo MapOrd[K, V]) SortByValue(fn func(a, b V) cmp.Ordering)

SortByValue sorts the ordered MapOrd[K, V] by the values using a custom comparison function.

Parameters:

- fn func(a, b V) cmp.Ordering: The custom comparison function used for sorting the values.

Example usage:

hmapo.SortByValue(func(a, b g.Int) cmp.Ordering { return a.Cmp(b) })

func (MapOrd[K, V]) String

func (mo MapOrd[K, V]) String() string

String returns a string representation of the ordered Map.

func (MapOrd[K, V]) ToMap added in v1.0.194

func (mo MapOrd[K, V]) ToMap() Map[K, V]

ToMap converts the ordered Map to a standard Map.

func (MapOrd[K, V]) ToMapSafe added in v1.0.194

func (mo MapOrd[K, V]) ToMapSafe() *MapSafe[K, V]

ToMapSafe converts a ordered Map to a thread-safe Map.

func (MapOrd[K, V]) Transform added in v1.0.89

func (mo MapOrd[K, V]) Transform(fn func(MapOrd[K, V]) MapOrd[K, V]) MapOrd[K, V]

Transform applies a transformation function to the MapOrd and returns the result.

func (MapOrd[K, V]) Values

func (mo MapOrd[K, V]) Values() Slice[V]

Values returns an Slice containing all the values in the ordered Map.

type MapOrdEntry added in v1.0.153

type MapOrdEntry[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapOrdEntry provides a view into a single key of an ordered Map (MapOrd), enabling fluent insertion, mutation, and deletion while preserving entry order.

func (MapOrdEntry[K, V]) Delete added in v1.0.153

func (e MapOrdEntry[K, V]) Delete() Option[V]

Delete removes the key from the Map. Returns Some(removed_value) if present, None otherwise.

func (MapOrdEntry[K, V]) Get added in v1.0.153

func (e MapOrdEntry[K, V]) Get() Option[V]

Get returns Some(value) if present, otherwise None.

func (MapOrdEntry[K, V]) OrDefault added in v1.0.153

func (e MapOrdEntry[K, V]) OrDefault() Option[V]

OrDefault inserts V's zero value if the key is vacant. Returns Some(existing_value) if key was present, None otherwise.

func (MapOrdEntry[K, V]) OrSet added in v1.0.153

func (e MapOrdEntry[K, V]) OrSet(value V) Option[V]

OrSet inserts value if the key is vacant. Returns Some(existing_value) if key was present, None otherwise.

func (MapOrdEntry[K, V]) OrSetBy added in v1.0.153

func (e MapOrdEntry[K, V]) OrSetBy(fn func() V) Option[V]

OrSetBy inserts the value produced by fn if the key is vacant. Returns Some(existing_value) if key was present, None otherwise.

func (MapOrdEntry[K, V]) Set added in v1.0.153

func (e MapOrdEntry[K, V]) Set(value V) Option[V]

Set sets the value for the specified key in the ordered map. Returns Some(previous_value) if the key existed, or None if it was newly inserted.

func (MapOrdEntry[K, V]) Transform added in v1.0.155

func (e MapOrdEntry[K, V]) Transform(fn func(V) V) Option[V]

Transform applies fn to the value if it exists. Returns Some(updated_value) if key was present, None otherwise.

type MapSafe added in v1.0.111

type MapSafe[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapSafe is a concurrent-safe generic map built on sync.Map.

func NewMapSafe added in v1.0.111

func NewMapSafe[K comparable, V any]() *MapSafe[K, V]

NewMapSafe creates a new instance of MapSafe.

func (*MapSafe[K, V]) Clear added in v1.0.111

func (ms *MapSafe[K, V]) Clear()

Clear removes all key-value pairs from the MapSafe.

func (*MapSafe[K, V]) Clone added in v1.0.111

func (ms *MapSafe[K, V]) Clone() *MapSafe[K, V]

Clone creates a deep copy of the MapSafe.

func (*MapSafe[K, V]) Contains added in v1.0.111

func (ms *MapSafe[K, V]) Contains(key K) bool

Contains checks if the MapSafe contains the specified key.

func (*MapSafe[K, V]) Copy added in v1.0.111

func (ms *MapSafe[K, V]) Copy(src *MapSafe[K, V])

Copy performs a deep copy of the source MapSafe's pairs into the current map.

func (*MapSafe[K, V]) Delete added in v1.0.111

func (ms *MapSafe[K, V]) Delete(keys ...K)

Delete removes the specified keys from the MapSafe.

func (*MapSafe[K, V]) Empty added in v1.0.111

func (ms *MapSafe[K, V]) Empty() bool

Empty checks if the MapSafe is empty.

func (*MapSafe[K, V]) Entry added in v1.0.166

func (ms *MapSafe[K, V]) Entry(key K) MapSafeEntry[K, V]

Entry returns a MapSafeEntry for a given key, allowing for more complex atomic operations.

func (*MapSafe[K, V]) Eq added in v1.0.111

func (ms *MapSafe[K, V]) Eq(other *MapSafe[K, V]) bool

Eq checks if two MapSafes are equal by deep-comparing their values.

func (*MapSafe[K, V]) Get added in v1.0.111

func (ms *MapSafe[K, V]) Get(key K) Option[V]

Get retrieves the value associated with the given key.

func (*MapSafe[K, V]) Invert added in v1.0.111

func (ms *MapSafe[K, V]) Invert() *MapSafe[any, K]

Invert inverts keys and values. The new map will also follow the pointer-storage rule.

func (*MapSafe[K, V]) Iter added in v1.0.111

func (ms *MapSafe[K, V]) Iter() SeqMap[K, V]

Iter provides a thread-safe iterator over the MapSafe's key-value pairs.

func (*MapSafe[K, V]) Keys added in v1.0.111

func (ms *MapSafe[K, V]) Keys() Slice[K]

Keys returns a slice of the MapSafe's keys.

func (*MapSafe[K, V]) Len added in v1.0.111

func (ms *MapSafe[K, V]) Len() int

Len returns the number of key-value pairs in the MapSafe.

func (*MapSafe[K, V]) Ne added in v1.0.111

func (ms *MapSafe[K, V]) Ne(other *MapSafe[K, V]) bool

Ne checks if two MapSafes are not equal.

func (*MapSafe[K, V]) NotEmpty added in v1.0.111

func (ms *MapSafe[K, V]) NotEmpty() bool

NotEmpty checks if the MapSafe is not empty.

func (*MapSafe[K, V]) Print added in v1.0.111

func (ms *MapSafe[K, V]) Print() *MapSafe[K, V]

Print writes the MapSafe to standard output.

func (*MapSafe[K, V]) Println added in v1.0.122

func (ms *MapSafe[K, V]) Println() *MapSafe[K, V]

Println writes the MapSafe to standard output with a newline.

func (*MapSafe[K, V]) Set added in v1.0.111

func (ms *MapSafe[K, V]) Set(key K, value V) Option[V]

Set stores the value for the given key, returning the previous value if it existed.

func (*MapSafe[K, V]) String added in v1.0.111

func (ms *MapSafe[K, V]) String() string

String returns a string representation of the MapSafe.

func (*MapSafe[K, V]) Values added in v1.0.111

func (ms *MapSafe[K, V]) Values() Slice[V]

Values returns a slice of the MapSafe's values.

type MapSafeEntry added in v1.0.166

type MapSafeEntry[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapSafeEntry provides a view into a single key of a concurrent-safe Map. It exposes a fluent, chain-friendly interface for inspecting, inserting, mutating, or deleting a value with a single key lookup.

func (MapSafeEntry[K, V]) Delete added in v1.0.166

func (e MapSafeEntry[K, V]) Delete() Option[V]

Delete atomically retrieves and removes the value for the key from the map. Returns Some(value) if it existed, otherwise None.

func (MapSafeEntry[K, V]) Get added in v1.0.166

func (e MapSafeEntry[K, V]) Get() Option[V]

Get returns Some(value) if the key exists, otherwise None.

func (MapSafeEntry[K, V]) OrDefault added in v1.0.166

func (e MapSafeEntry[K, V]) OrDefault() Option[V]

OrDefault inserts V's zero value if the key is vacant. Returns the value that is in the map after the operation.

func (MapSafeEntry[K, V]) OrSet added in v1.0.166

func (e MapSafeEntry[K, V]) OrSet(value V) Option[V]

OrSet inserts `value` if the key is vacant. Returns the value that is in the map after the operation (either the old or the new one).

func (MapSafeEntry[K, V]) OrSetBy added in v1.0.166

func (e MapSafeEntry[K, V]) OrSetBy(fn func() V) Option[V]

OrSetBy inserts the value produced by `fn` if the key is vacant. `fn` is only called if needed. Returns the value that is in the map after the operation.

func (MapSafeEntry[K, V]) Set added in v1.0.166

func (e MapSafeEntry[K, V]) Set(value V) Option[V]

Set unconditionally sets the value for the key. Returns Some(old_value) if the key was already present, otherwise None.

func (MapSafeEntry[K, V]) Transform added in v1.0.166

func (e MapSafeEntry[K, V]) Transform(fn func(V) V) Option[V]

Transform atomically applies `fn` to the existing value if present. The function `fn` takes the old value and returns the new value. This operation is implemented using a lock-free Compare-And-Swap (CAS) loop. Returns Some(updated_value) if successful, or None if the key was missing.

type Named added in v1.0.130

type Named Map[String, any]

Named is a map-like type that stores key-value pairs for resolving named placeholders in Sprintf.

type Option

type Option[T any] struct {
	// contains filtered or unexported fields
}

Option is a generic struct for representing an optional value.

func None

func None[T any]() Option[T]

None creates an Option representing no value.

func OptionOf added in v1.0.97

func OptionOf[T any](value T, ok bool) Option[T]

OptionOf creates an Option[T] based on the provided value and a boolean flag. If ok is true, it returns Some(value). Otherwise, it returns None.

func Some

func Some[T any](value T) Option[T]

Some creates an Option containing a value.

func TransformOption added in v1.0.93

func TransformOption[T, U any](o Option[T], fn func(T) Option[U]) Option[U]

TransformOption applies the given function to the value inside the Option, producing a new Option with the transformed value. If the input Option is None, the output Option will also be None. Parameters:

  • o: The input Option to map over.
  • fn: The function that returns an Option to apply to the value inside the Option.

Returns:

A new Option with the transformed value, or None if the input was None.

func (Option[T]) Expect

func (o Option[T]) Expect(msg string) T

Expect returns the value held in the Option. If the Option is None, it panics with the provided message.

func (Option[T]) IsNone

func (o Option[T]) IsNone() bool

IsNone returns true if the Option represents no value.

func (Option[T]) IsSome

func (o Option[T]) IsSome() bool

IsSome returns true if the Option contains a value.

func (Option[T]) Option added in v1.0.184

func (o Option[T]) Option() (T, bool)

func (Option[T]) Result added in v1.0.165

func (o Option[T]) Result(err error) Result[T]

Result converts an Option into a Result. If the Option is Some, it returns an Ok Result with the value. If the Option is None, it returns an Err Result with the provided error.

func (Option[T]) Some

func (o Option[T]) Some() T

Some returns the contained value of the Option.

WARNING: If the Option is None, this method will return the zero value for type T. Always check IsSome() before calling this method, or use safer alternatives like Unwrap(), or UnwrapOr().

func (Option[T]) String added in v1.0.60

func (o Option[T]) String() string

String returns a string representation of the Option. If the Option contains a value, it returns a string in the format "Some(value)". Otherwise, it returns "None".

func (Option[T]) Then

func (o Option[T]) Then(fn func(T) Option[T]) Option[T]

Then applies the function fn to the value inside the Option and returns a new Option. If the Option is None, it returns the same Option without applying fn.

func (Option[T]) Unwrap

func (o Option[T]) Unwrap() T

Unwrap returns the value held in the Option. If the Option is None, it panics.

func (Option[T]) UnwrapOr

func (o Option[T]) UnwrapOr(value T) T

UnwrapOr returns the value held in the Option. If the Option is None, it returns the provided default value.

func (Option[T]) UnwrapOrDefault

func (o Option[T]) UnwrapOrDefault() T

UnwrapOrDefault returns the contained value if Some; otherwise returns the zero value for T.

type Pair

type Pair[K, V any] = iter.Pair[K, V]

Pair is a struct representing a key-value Pair for MapOrd.

type Result

type Result[T any] struct {
	// contains filtered or unexported fields
}

Result is a generic struct for representing a result value along with an error.

func Eprint added in v1.0.146

func Eprint[T ~string](format T, args ...any) Result[int]

Eprint formats according to a format specifier and writes to os.Stderr. It returns a Result containing the number of bytes written or an error.

Example:

g.Eprint("Error: {}", "file not found")

func Eprintln added in v1.0.146

func Eprintln[T ~string](format T, args ...any) Result[int]

Eprintln formats according to a format specifier, appends a newline, and writes to os.Stderr. It returns a Result containing the number of bytes written or an error.

Example:

g.Eprintln("Error: {}", "permission denied")

func Err

func Err[T any](err error) Result[T]

Err returns a new Result[T] containing the given error.

func Ok

func Ok[T any](value T) Result[T]

Ok returns a new Result[T] containing the given value.

func Print added in v1.0.122

func Print[T ~string](format T, args ...any) Result[int]

Print formats according to a format specifier and writes to os.Stdout. It returns a Result containing the number of bytes written or an error.

Example:

g.Print("Hello, {}!\n", "world")

func Println added in v1.0.122

func Println[T ~string](format T, args ...any) Result[int]

Println formats according to a format specifier, appends a newline, and writes to os.Stdout. It returns a Result containing the number of bytes written or an error.

Example:

g.Println("Hello, {}", "world")

func ResultOf added in v1.0.52

func ResultOf[T any](value T, err error) Result[T]

ResultOf returns a new Result[T] based on the provided value and error. If err is not nil, it returns an Err Result. Otherwise, it returns an Ok Result.

func TransformResult added in v1.0.93

func TransformResult[T, U any](r Result[T], fn func(T) Result[U]) Result[U]

TransformResult applies a function to the contained Ok value, returning a new Result. If the input Result is Err, the error is propagated. This is also known as 'and_then' or 'flat_map'.

func TransformResultOf added in v1.0.93

func TransformResultOf[T, U any](r Result[T], fn func(T) (U, error)) Result[U]

TransformResultOf applies a function that returns a (value, error) tuple to the contained Ok value. If the input Result is Err, the error is propagated.

func Write added in v1.0.146

func Write[T ~string](w io.Writer, format T, args ...any) Result[int]

Write formats according to a format specifier and writes to w. It returns a Result containing the number of bytes written or an error.

Example:

res := g.Write(os.Stdout, "Hello, {}!\n", "world")
if res.IsErr() { log.Fatal(res.Err()) }

func Writeln added in v1.0.146

func Writeln[T ~string](w io.Writer, format T, args ...any) Result[int]

Writeln formats according to a format specifier, appends a newline, and writes to w. It returns a Result containing the number of bytes written or an error.

Example:

res := g.Writeln(os.Stdout, "Hello, {}", "world")
if res.IsErr() { log.Fatal(res.Err()) }

func (Result[T]) Err

func (r Result[T]) Err() error

Err returns the error held in the Result. If the result is Ok, it returns nil.

func (Result[T]) Expect

func (r Result[T]) Expect(msg string) T

Expect returns the value held in the Result. If the Result is Err, it panics with the provided message.

func (Result[T]) IsErr

func (r Result[T]) IsErr() bool

IsErr returns true if the Result contains an error.

func (Result[T]) IsOk

func (r Result[T]) IsOk() bool

IsOk returns true if the Result contains a value (no error).

func (Result[T]) MapErr added in v1.0.165

func (r Result[T]) MapErr(fn func(error) error) Result[T]

MapErr transforms the error in an Err Result by applying a function to it. It is useful for custom error handling, like replacing one error with another. If the Result is Ok, it does nothing.

func (Result[T]) Ok

func (r Result[T]) Ok() T

Ok returns the value held in the Result.

WARNING: If the Result contains an error, this method will return the zero value for type T. Always check IsOk() before calling this method, or use safer alternatives like Result(), Unwrap(), or UnwrapOr().

func (Result[T]) Option added in v1.0.52

func (r Result[T]) Option() Option[T]

Option converts a Result into an Option. If the Result is Ok, it returns Some(value). If the Result is Err, it returns None.

func (Result[T]) Result

func (r Result[T]) Result() (T, error)

Result returns the value and error, conforming to the standard Go multi-value return pattern.

func (Result[T]) String added in v1.0.60

func (r Result[T]) String() string

String returns a string representation of the Result.

func (Result[T]) Then

func (r Result[T]) Then(fn func(T) Result[T]) Result[T]

Then applies a function to the contained value (if Ok) and returns the result. If the Result is Err, it returns the same Err without applying the function.

func (Result[T]) ThenOf added in v1.0.52

func (r Result[T]) ThenOf(fn func(T) (T, error)) Result[T]

ThenOf applies a function to the contained value (if Ok) and returns a new Result based on the returned (T, error) tuple.

func (Result[T]) Unwrap

func (r Result[T]) Unwrap() T

Unwrap returns the value held in the Result. If the Result is Err, it panics.

func (Result[T]) UnwrapOr

func (r Result[T]) UnwrapOr(value T) T

UnwrapOr returns the value held in the Result. If the Result is Err, it returns the provided default value.

func (Result[T]) UnwrapOrDefault

func (r Result[T]) UnwrapOrDefault() T

UnwrapOrDefault returns the contained value if Ok, otherwise returns the zero value for T.

type SeqDeque added in v1.0.181

type SeqDeque[V any] iter.Seq[V]

SeqDeque is an iterator over sequences of Deque values.

func (SeqDeque[V]) All added in v1.0.181

func (seq SeqDeque[V]) All(fn func(v V) bool) bool

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(V) 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:

deque := g.DequeOf(1, 2, 3, 4, 5, 6, 7, -1, -2)
isPositive := func(num int) bool { return num > 0 }
allPositive := deque.Iter().All(isPositive)

The resulting allPositive will be true if all elements returned by the iterator are positive.

func (SeqDeque[V]) Any added in v1.0.181

func (seq SeqDeque[V]) Any(fn func(V) bool) bool

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(V) 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:

deque := g.DequeOf(1, 3, 5, 7, 9)
isEven := func(num int) bool { return num%2 == 0 }
anyEven := deque.Iter().Any(isEven)

The resulting anyEven will be true if at least one element returned by the iterator is even.

func (SeqDeque[V]) Chain added in v1.0.181

func (seq SeqDeque[V]) Chain(seqs ...SeqDeque[V]) SeqDeque[V]

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 ([]SeqDeque[V]): Other iterators to be concatenated with the current iterator.

Returns:

- SeqDeque[V]: A new iterator containing elements from the current iterator and the provided iterators.

Example usage:

iter1 := g.DequeOf(1, 2, 3).Iter()
iter2 := g.DequeOf(4, 5, 6).Iter()
iter1.Chain(iter2).Collect().Print()

Output: Deque[1, 2, 3, 4, 5, 6]

The resulting iterator will contain elements from both iterators in the specified order.

func (SeqDeque[V]) Chunks added in v1.0.181

func (seq SeqDeque[V]) Chunks(n Int) SeqSlices[V]

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:

deque := g.DequeOf(1, 2, 3, 4, 5, 6)
chunks := deque.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 (SeqDeque[V]) Collect added in v1.0.181

func (seq SeqDeque[V]) Collect() *Deque[V]

Collect gathers all elements from the iterator into a Deque.

func (SeqDeque[V]) Combinations added in v1.0.181

func (seq SeqDeque[V]) Combinations(size Int) SeqSlices[V]

Combinations generates all combinations of length 'n' from the sequence.

func (SeqDeque[V]) Context added in v1.0.181

func (seq SeqDeque[V]) Context(ctx context.Context) SeqDeque[V]

Context allows the iteration to be controlled with a context.Context.

func (SeqDeque[V]) Count added in v1.0.181

func (seq SeqDeque[V]) Count() Int

Count consumes the iterator, counting the number of iterations and returning it.

func (SeqDeque[V]) Counter added in v1.0.181

func (seq SeqDeque[V]) Counter() SeqMapOrd[any, Int]

Counter returns a map where each key is a unique element from the deque and each value is the count of how many times that element appears.

The function counts the occurrences of each element in the deque and returns a map representing the unique elements and their respective counts. This method uses iter.Counter from the iter package.

Returns:

- SeqMapOrd[V, Int]: with keys representing the unique elements in the deque and values representing the counts of those elements.

Example usage:

deque := g.DequeOf(1, 2, 3, 1, 2, 1)
counts := deque.Iter().Counter()
// The counts map will contain:
// 1 -> 3 (since 1 appears three times)
// 2 -> 2 (since 2 appears two times)
// 3 -> 1 (since 3 appears once)

func (SeqDeque[V]) Cycle added in v1.0.181

func (seq SeqDeque[V]) Cycle() SeqDeque[V]

Cycle returns an iterator that endlessly repeats the elements of the current sequence.

func (SeqDeque[V]) Dedup added in v1.0.181

func (seq SeqDeque[V]) Dedup() SeqDeque[V]

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: - SeqDeque[V]: A new iterator with consecutive duplicates removed.

Example usage:

deque := g.DequeOf(1, 2, 2, 3, 4, 4, 4, 5)
iter := deque.Iter().Dedup()
result := iter.Collect()
result.Print()

Output: Deque[1, 2, 3, 4, 5]

The resulting iterator will contain only unique elements, removing consecutive duplicates.

func (SeqDeque[V]) Enumerate added in v1.0.181

func (seq SeqDeque[V]) Enumerate() SeqMapOrd[Int, V]

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.DequeOf("bbb", "ddd", "xxx", "aaa", "ccc").
	Iter().
	Enumerate().
	Collect()

ps.Print()

Output: MapOrd{0:bbb, 1:ddd, 2:xxx, 3:aaa, 4:ccc}

func (SeqDeque[V]) Exclude added in v1.0.181

func (seq SeqDeque[V]) Exclude(fn func(V) bool) SeqDeque[V]

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(V) bool): The function to be applied to each element of the iterator to determine if it should be excluded from the result.

Returns:

- SeqDeque[V]: A new iterator containing the elements that do not satisfy the given condition.

Example usage:

deque := g.DequeOf(1, 2, 3, 4, 5)
notEven := deque.Iter().
	Exclude(
		func(val int) bool {
			return val%2 == 0
		}).
	Collect()
notEven.Print()

Output: Deque[1, 3, 5]

The resulting iterator will contain only the elements that do not satisfy the provided function.

func (SeqDeque[V]) Filter added in v1.0.181

func (seq SeqDeque[V]) Filter(fn func(V) bool) SeqDeque[V]

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(V) bool): The function to be applied to each element of the iterator to determine if it should be included in the result.

Returns:

- SeqDeque[V]: A new iterator containing the elements that satisfy the given condition.

Example usage:

deque := g.DequeOf(1, 2, 3, 4, 5)
even := deque.Iter().
	Filter(
		func(val int) bool {
			return val%2 == 0
		}).
	Collect()
even.Print()

Output: Deque[2, 4].

The resulting iterator will contain only the elements that satisfy the provided function.

func (SeqDeque[V]) FilterMap added in v1.0.184

func (seq SeqDeque[V]) FilterMap(fn func(V) Option[V]) SeqDeque[V]

FilterMap applies a function to each element and filters out None results.

The function transforms and filters elements in a single pass. Elements where the function returns None are filtered out, and elements where it returns Some are unwrapped and included in the result.

Params:

  • fn (func(V) Option[V]): The function that transforms and filters elements. Returns Some(value) to include the transformed element, or None to filter it out.

Returns:

- SeqDeque[V]: A sequence containing only the successfully transformed elements.

Example usage:

deque := g.DequeOf(1, 2, 3, 4, 5)
result := deque.Iter().FilterMap(func(n int) g.Option[int] {
	if n%2 == 0 {
		return g.Some(n * 10)
	}
	return g.None[int]()
}).Collect()
result.Print() // Deque[20, 40]

func (SeqDeque[V]) Find added in v1.0.181

func (seq SeqDeque[V]) Find(fn func(v V) bool) Option[V]

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(V) 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.DequeOf(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 (SeqDeque[V]) First added in v1.0.191

func (seq SeqDeque[V]) First() Option[V]

First returns the first element from the sequence.

func (SeqDeque[V]) FlatMap added in v1.0.184

func (seq SeqDeque[V]) FlatMap(fn func(V) SeqDeque[V]) SeqDeque[V]

FlatMap applies a function to each element and flattens the results into a single sequence.

The function transforms each element into a new SeqDeque and then flattens all resulting sequences into a single sequence.

Params:

  • fn (func(V) SeqDeque[V]): The function that transforms each element into a SeqDeque.

Returns:

- SeqDeque[V]: A flattened sequence containing all elements from the transformed sequences.

Example usage:

deque := g.DequeOf(1, 2, 3)
result := deque.Iter().FlatMap(func(n int) g.SeqDeque[int] {
	return g.DequeOf(n, n*10).Iter()
}).Collect()
result.Print() // Deque[1, 10, 2, 20, 3, 30]

func (SeqDeque[V]) Flatten added in v1.0.181

func (seq SeqDeque[V]) Flatten() SeqDeque[V]

Flatten flattens an iterator containing slices 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:

- SeqDeque[V]: A single iterator containing elements from the sequence of iterators.

Example usage:

nestedDeque := g.DequeOf(
	1,
	g.SliceOf(2, 3),
	"abc",
	g.SliceOf("def", "ghi"),
	g.SliceOf(4.5, 6.7),
)

nestedDeque.Iter().Flatten().Collect().Print()

Output: Deque[1, 2, 3, abc, def, ghi, 4.5, 6.7]

The resulting iterator will contain elements from each iterator in sequence.

func (SeqDeque[V]) Fold added in v1.0.181

func (seq SeqDeque[V]) Fold(init V, fn func(acc, val V) V) V

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 V.

Returns:

- T: The accumulated value after applying the function to all elements.

Example usage:

deque := g.DequeOf(1, 2, 3, 4, 5)
sum := deque.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 (SeqDeque[V]) ForEach added in v1.0.181

func (seq SeqDeque[V]) ForEach(fn func(v V))

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(V)): The function to apply to each element.

Example usage:

iter := g.DequeOf(1, 2, 3, 4, 5).Iter()
iter.ForEach(func(val V) {
    fmt.Println(val) // Replace this with the function logic you need.
})

The provided function will be applied to each element in the iterator.

func (SeqDeque[V]) GroupBy added in v1.0.181

func (seq SeqDeque[V]) GroupBy(fn func(a, b V) bool) SeqSlices[V]

GroupBy groups consecutive elements of the sequence based on a custom equality function.

The provided function `fn` takes two consecutive elements `a` and `b` and returns `true` if they belong to the same group, or `false` if a new group should start. The function returns a `SeqSlices[V]`, where each `[]V` represents a group of consecutive elements that satisfy the provided equality condition.

Notes:

  • Each group is returned as a copy of the elements, since `SeqDeque` does not guarantee that elements share the same backing array.

Parameters:

  • fn (func(a, b V) bool): Function that determines whether two consecutive elements belong to the same group.

Returns:

  • SeqSlices[V]: An iterator yielding slices, each containing one group.

Example usage:

deque := g.DequeOf(1, 1, 2, 3, 2, 3, 4)
groups := deque.Iter().GroupBy(func(a, b int) bool { return a <= b }).Collect()
// Output: [Slice[1, 1, 2, 3] Slice[2, 3, 4]]

The resulting iterator will yield groups of consecutive elements according to the provided function.

func (SeqDeque[V]) Inspect added in v1.0.181

func (seq SeqDeque[V]) Inspect(fn func(v V)) SeqDeque[V]

Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.

func (SeqDeque[V]) Intersperse added in v1.0.181

func (seq SeqDeque[V]) Intersperse(sep V) SeqDeque[V]

Intersperse inserts the provided separator between elements of the iterator.

The function creates a new iterator that inserts the given separator between each consecutive pair of elements in the original iterator.

Params:

- sep (V): The separator to intersperse between elements.

Returns:

- SeqDeque[V]: An iterator containing elements with the separator interspersed.

Example usage:

g.DequeOf("Hello", "World", "!").
	Iter().
	Intersperse(" ").
	Collect().
	Print()

Output: "Hello World !".

The resulting iterator will contain elements with the separator interspersed.

func (SeqDeque[V]) Last added in v1.0.191

func (seq SeqDeque[V]) Last() Option[V]

Last returns the last element from the sequence.

func (SeqDeque[V]) Map added in v1.0.181

func (seq SeqDeque[V]) Map(transform func(V) V) SeqDeque[V]

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(V) V): The function used to transform elements.

Returns:

- SeqDeque[V]: A iterator containing elements transformed by the provided function.

Example usage:

deque := g.DequeOf(1, 2, 3)
doubled := deque.
	Iter().
	Map(
		func(val int) int {
			return val * 2
		}).
	Collect()
doubled.Print()

Output: Deque[2, 4, 6].

The resulting iterator will contain elements transformed by the provided function.

func (SeqDeque[V]) MaxBy added in v1.0.181

func (seq SeqDeque[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]

MaxBy returns the maximum element in the sequence using the provided comparison function.

func (SeqDeque[V]) MinBy added in v1.0.181

func (seq SeqDeque[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]

MinBy returns the minimum element in the sequence using the provided comparison function.

func (*SeqDeque[V]) Next added in v1.0.189

func (seq *SeqDeque[V]) Next() Option[V]

Next extracts the next element from the iterator and advances it.

This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements.

Returns: - Option[V]: Some(value) if an element exists, None if the iterator is exhausted.

func (SeqDeque[V]) Nth added in v1.0.181

func (seq SeqDeque[V]) Nth(n Int) Option[V]

Nth returns the nth element (0-indexed) in the sequence.

func (SeqDeque[V]) Parallel added in v1.0.183

func (seq SeqDeque[V]) Parallel(workers ...Int) SeqDequePar[V]

Parallel converts a sequential deque iterator into a parallel iterator with the specified number of workers. If no worker count is provided, it defaults to the number of CPU cores. The parallel iterator processes elements concurrently using a worker pool.

func (SeqDeque[V]) Partition added in v1.0.181

func (seq SeqDeque[V]) Partition(fn func(v V) bool) (*Deque[V], *Deque[V])

Partition divides the elements of the iterator into two separate deques 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 deque, while those for which 'fn' returns false are collected into the right deque.

Params:

- fn (func(V) bool): The predicate function used to determine the placement of elements.

Returns:

- (Deque[V], Deque[V]): Two deques representing elements that satisfy and don't satisfy the predicate, respectively.

Example usage:

evens, odds := g.DequeOf(1, 2, 3, 4, 5).
	Iter().
	Partition(
		func(v int) bool {
			return v%2 == 0
		})

fmt.Println("Even numbers:", evens) // Output: Even numbers: Deque[2, 4]
fmt.Println("Odd numbers:", odds)   // Output: Odd numbers: Deque[1, 3, 5]

The resulting two deques will contain elements separated based on whether they satisfy the predicate or not.

func (SeqDeque[V]) Permutations added in v1.0.181

func (seq SeqDeque[V]) Permutations() SeqSlices[V]

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:

deque := g.DequeOf(1, 2, 3)
perms := deque.Iter().Permutations().Collect()
for _, perm := range perms {
    fmt.Println(perm)
}

Output: Slice[1, 2, 3] Slice[2, 1, 3] Slice[3, 1, 2] Slice[1, 3, 2] Slice[2, 3, 1] Slice[3, 2, 1]

The resulting iterator will contain iterators representing all possible permutations of the elements in the original iterator.

func (SeqDeque[V]) Pull added in v1.0.181

func (seq SeqDeque[V]) Pull() (func() (V, bool), func())

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 (SeqDeque[V]) Range added in v1.0.181

func (seq SeqDeque[V]) Range(fn func(v V) bool)

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(V) bool): The function that evaluates elements for continuation of iteration.

Example usage:

iter := g.DequeOf(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 (SeqDeque[V]) Reduce added in v1.0.181

func (seq SeqDeque[V]) Reduce(fn func(a, b V) V) Option[V]

Reduce aggregates elements of the sequence using the provided function. The first element of the sequence is used as the initial accumulator value. If the sequence is empty, it returns None[V].

Params:

  • fn (func(V, V) V): Function that combines two values into one.

Returns:

  • Option[V]: The accumulated value wrapped in Some, or None if the sequence is empty.

Example:

deque := g.DequeOf(1, 2, 3, 4, 5)
product := deque.Iter().Reduce(func(a, b int) int { return a * b })
if product.IsSome() {
    fmt.Println(product.Some()) // 120
} else {
    fmt.Println("empty")
}

func (SeqDeque[V]) Scan added in v1.0.184

func (seq SeqDeque[V]) Scan(init V, fn func(acc, val V) V) SeqDeque[V]

Scan applies a function to each element and produces a sequence of successive accumulated results.

The function takes an initial value and applies the provided function to each element along with the accumulated value, producing a new sequence where each element is the result of the accumulation. The initial value is included as the first element.

Params:

  • init (V): The initial value for the accumulation.
  • fn (func(acc, val V) V): The function that combines the accumulator with each element.

Returns:

- SeqDeque[V]: A sequence containing the initial value and all accumulated results.

Example usage:

deque := g.DequeOf(1, 2, 3, 4, 5)
result := deque.Iter().Scan(0, func(acc, val int) int {
	return acc + val
}).Collect()
result.Print() // Deque[0, 1, 3, 6, 10, 15]

func (SeqDeque[V]) Skip added in v1.0.181

func (seq SeqDeque[V]) Skip(n uint) SeqDeque[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:

- SeqDeque[V]: An iterator that starts after skipping the first n elements.

Example usage:

iter := g.DequeOf(1, 2, 3, 4, 5, 6).Iter()
iter.Skip(3).Collect().Print()

Output: Deque[4, 5, 6]

The resulting iterator will start after skipping the specified number of elements.

func (SeqDeque[V]) SortBy added in v1.0.181

func (seq SeqDeque[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqDeque[V]

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 V, and return true if 'a' should be ordered before 'b', and false otherwise.

Example:

g.DequeOf("a", "c", "b").
	Iter().
	SortBy(func(a, b string) cmp.Ordering { return b.Cmp(a) }).
	Collect().
	Print()

Output: Deque[c, b, a]

The returned iterator is of type SeqDeque[V], which implements the iterator interface for further iteration over the sorted elements.

func (SeqDeque[V]) StepBy added in v1.0.181

func (seq SeqDeque[V]) StepBy(n uint) SeqDeque[V]

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: - SeqDeque[V]: A new iterator that produces elements from the original iterator with a step size of N.

Example usage:

deque := g.DequeOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
iter := deque.Iter().StepBy(3)
result := iter.Collect()
result.Print()

Output: Deque[1, 4, 7, 10]

The resulting iterator will produce elements from the original iterator with a step size of N.

func (SeqDeque[V]) Take added in v1.0.181

func (seq SeqDeque[V]) Take(n uint) SeqDeque[V]

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 (SeqDeque[V]) ToChan added in v1.0.181

func (seq SeqDeque[V]) ToChan(ctxs ...context.Context) chan V

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.DequeOf(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 (SeqDeque[V]) Unique added in v1.0.181

func (seq SeqDeque[V]) Unique() SeqDeque[V]

Unique returns an iterator with only unique elements.

The function returns an iterator containing only the unique elements from the original iterator.

Returns:

- SeqDeque[V]: An iterator containing unique elements from the original iterator.

Example usage:

deque := g.DequeOf(1, 2, 3, 2, 4, 5, 3)
unique := deque.Iter().Unique().Collect()
unique.Print()

Output: Deque[1, 2, 3, 4, 5].

The resulting iterator will contain only unique elements from the original iterator.

func (SeqDeque[V]) Windows added in v1.0.181

func (seq SeqDeque[V]) Windows(n Int) SeqSlices[V]

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:

- n (int): The size of each window.

Returns:

- SeqSlices[V]: An iterator yielding sliding windows of elements of the specified size.

Example usage:

deque := g.DequeOf(1, 2, 3, 4, 5, 6)
windows := deque.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 (SeqDeque[V]) Zip added in v1.0.181

func (seq SeqDeque[V]) Zip(two SeqDeque[V]) SeqMapOrd[any, any]

Zip combines elements from the current sequence and another sequence into pairs, creating an ordered map with identical keys and values of type V.

type SeqDequePar added in v1.0.183

type SeqDequePar[V any] struct {
	// contains filtered or unexported fields
}

SeqDequePar is a parallel iterator over a deque of elements of type T. It uses a fixed-size pool of worker goroutines to process elements concurrently.

func (SeqDequePar[V]) All added in v1.0.183

func (p SeqDequePar[V]) All(fn func(V) bool) bool

All returns true only if fn returns true for every element. It stops early on the first false.

func (SeqDequePar[V]) Any added in v1.0.183

func (p SeqDequePar[V]) Any(fn func(V) bool) bool

Any returns true if fn returns true for any element. It stops early on the first true.

func (SeqDequePar[V]) Chain added in v1.0.183

func (p SeqDequePar[V]) Chain(others ...SeqDequePar[V]) SeqDequePar[V]

Chain concatenates this SeqDequePar with others, preserving full parallelism. Each sequence runs with its own worker pool in parallel.

func (SeqDequePar[V]) Collect added in v1.0.183

func (p SeqDequePar[V]) Collect() *Deque[V]

Collect gathers all processed elements into a Deque.

func (SeqDequePar[V]) Count added in v1.0.183

func (p SeqDequePar[V]) Count() Int

Count returns the total number of elements processed.

func (SeqDequePar[V]) Exclude added in v1.0.183

func (p SeqDequePar[V]) Exclude(fn func(V) bool) SeqDequePar[V]

Exclude removes elements for which fn returns true, in parallel.

func (SeqDequePar[V]) Filter added in v1.0.183

func (p SeqDequePar[V]) Filter(fn func(V) bool) SeqDequePar[V]

Filter retains only elements where fn returns true.

func (SeqDequePar[V]) FilterMap added in v1.0.184

func (p SeqDequePar[V]) FilterMap(fn func(V) Option[V]) SeqDequePar[V]

FilterMap applies fn to each element in parallel, keeping only Some values.

func (SeqDequePar[V]) Find added in v1.0.183

func (p SeqDequePar[V]) Find(fn func(V) bool) Option[V]

Find returns the first element satisfying fn, or None if no such element exists.

func (SeqDequePar[V]) FlatMap added in v1.0.184

func (p SeqDequePar[V]) FlatMap(fn func(V) SeqDeque[V]) SeqDequePar[V]

FlatMap applies fn to each element in parallel, flattening the resulting sequences.

func (SeqDequePar[V]) Flatten added in v1.0.183

func (p SeqDequePar[V]) Flatten() SeqDequePar[V]

Flatten unpacks nested slices or arrays in the source, returning a flat parallel sequence.

func (SeqDequePar[V]) Fold added in v1.0.183

func (p SeqDequePar[V]) Fold(init V, fn func(acc, v V) V) V

Fold reduces all elements into a single value, using fn to accumulate results.

func (SeqDequePar[V]) ForEach added in v1.0.183

func (p SeqDequePar[V]) ForEach(fn func(V))

ForEach applies fn to each element without early exit.

func (SeqDequePar[V]) Inspect added in v1.0.183

func (p SeqDequePar[V]) Inspect(fn func(V)) SeqDequePar[V]

Inspect invokes fn on each element without altering the resulting sequence.

func (SeqDequePar[V]) Map added in v1.0.183

func (p SeqDequePar[V]) Map(fn func(V) V) SeqDequePar[V]

Map applies fn to each element.

func (SeqDequePar[V]) MaxBy added in v1.0.184

func (p SeqDequePar[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]

MaxBy returns the maximum element according to the comparison function.

func (SeqDequePar[V]) MinBy added in v1.0.184

func (p SeqDequePar[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]

MinBy returns the minimum element according to the comparison function.

func (SeqDequePar[V]) Partition added in v1.0.183

func (p SeqDequePar[V]) Partition(fn func(V) bool) (*Deque[V], *Deque[V])

func (SeqDequePar[V]) Range added in v1.0.183

func (p SeqDequePar[V]) Range(fn func(V) bool)

Range applies fn to each processed element in parallel, stopping on false.

func (SeqDequePar[V]) Reduce added in v1.0.183

func (p SeqDequePar[V]) Reduce(fn func(a, b V) V) Option[V]

Reduce aggregates elements of the parallel sequence using the provided function. The first received element is used as the initial accumulator. If the sequence is empty, returns None[V].

func (SeqDequePar[V]) Skip added in v1.0.183

func (p SeqDequePar[V]) Skip(n uint) SeqDequePar[V]

func (SeqDequePar[V]) StepBy added in v1.0.184

func (p SeqDequePar[V]) StepBy(n uint) SeqDequePar[V]

StepBy yields every nth element.

func (SeqDequePar[V]) Take added in v1.0.183

func (p SeqDequePar[V]) Take(n uint) SeqDequePar[V]

func (SeqDequePar[V]) Unique added in v1.0.183

func (p SeqDequePar[V]) Unique() SeqDequePar[V]

Unique removes duplicate elements, preserving the first occurrence.

type SeqHeap added in v1.0.181

type SeqHeap[V any] iter.Seq[V]

SeqHeap is an iterator over sequences of Heap values.

func (SeqHeap[V]) All added in v1.0.181

func (seq SeqHeap[V]) All(fn func(v V) bool) bool

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(V) 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:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5, 6, 7, -1, -2)
isPositive := func(num int) bool { return num > 0 }
allPositive := heap.Iter().All(isPositive)

The resulting allPositive will be true if all elements returned by the iterator are positive.

func (SeqHeap[V]) Any added in v1.0.181

func (seq SeqHeap[V]) Any(fn func(V) bool) bool

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(V) 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:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 3, 5, 7, 9)
isEven := func(num int) bool { return num%2 == 0 }
anyEven := heap.Iter().Any(isEven)

The resulting anyEven will be true if at least one element returned by the iterator is even.

func (SeqHeap[V]) Chain added in v1.0.181

func (seq SeqHeap[V]) Chain(seqs ...SeqHeap[V]) SeqHeap[V]

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 ([]SeqHeap[V]): Other iterators to be concatenated with the current iterator.

Returns:

- SeqHeap[V]: A new iterator containing elements from the current iterator and the provided iterators.

Example usage:

heap1 := g.NewHeap(cmp.Cmp[int])
heap1.Push(1, 2, 3)
heap2 := g.NewHeap(cmp.Cmp[int])
heap2.Push(4, 5, 6)
heap1.Iter().Chain(heap2.Iter()).Collect() // Creates new heap with all elements

The resulting iterator will contain elements from both iterators in the specified order.

func (SeqHeap[V]) Chunks added in v1.0.181

func (seq SeqHeap[V]) Chunks(n Int) SeqSlices[V]

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:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5, 6)
chunks := heap.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 (SeqHeap[V]) Collect added in v1.0.181

func (seq SeqHeap[V]) Collect(compareFn func(V, V) cmp.Ordering) *Heap[V]

Collect gathers all elements from the iterator into a new Heap with a custom comparison function.

func (SeqHeap[V]) Combinations added in v1.0.181

func (seq SeqHeap[V]) Combinations(size Int) SeqSlices[V]

Combinations generates all combinations of length 'n' from the sequence.

func (SeqHeap[V]) Context added in v1.0.181

func (seq SeqHeap[V]) Context(ctx context.Context) SeqHeap[V]

Context allows the iteration to be controlled with a context.Context.

func (SeqHeap[V]) Count added in v1.0.181

func (seq SeqHeap[V]) Count() Int

Count consumes the iterator, counting the number of iterations and returning it.

func (SeqHeap[V]) Counter added in v1.0.181

func (seq SeqHeap[V]) Counter() SeqMapOrd[any, Int]

Counter returns a map where each key is a unique element from the heap and each value is the count of how many times that element appears.

The function counts the occurrences of each element in the heap and returns a map representing the unique elements and their respective counts. This method uses iter.Counter from the iter package.

Returns:

- SeqMapOrd[V, Int]: with keys representing the unique elements in the heap and values representing the counts of those elements.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 1, 2, 1)
counts := heap.Iter().Counter()
// The counts map will contain:
// 1 -> 3 (since 1 appears three times)
// 2 -> 2 (since 2 appears two times)
// 3 -> 1 (since 3 appears once)

func (SeqHeap[V]) Cycle added in v1.0.181

func (seq SeqHeap[V]) Cycle() SeqHeap[V]

Cycle returns an iterator that endlessly repeats the elements of the current sequence.

func (SeqHeap[V]) Dedup added in v1.0.181

func (seq SeqHeap[V]) Dedup() SeqHeap[V]

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: - SeqHeap[V]: A new iterator with consecutive duplicates removed.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 2, 3, 4, 4, 4, 5)
iter := heap.Iter().Dedup()
result := iter.CollectWith(cmp.Cmp[int])
result.Iter().ForEach(func(v int) { fmt.Print(v, " ") })

Output: 1 2 3 4 5

The resulting iterator will contain only unique elements, removing consecutive duplicates.

func (SeqHeap[V]) Enumerate added in v1.0.181

func (seq SeqHeap[V]) Enumerate() SeqMapOrd[Int, V]

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:

heap := g.NewHeap(cmp.Cmp[g.String])
heap.Push("bbb", "ddd", "xxx", "aaa", "ccc")
ps := heap.Iter().
	Enumerate().
	Collect()

ps.Print()

Output: MapOrd{0:aaa, 1:bbb, 2:ccc, 3:ddd, 4:xxx}

func (SeqHeap[T]) Eq added in v1.0.181

func (seq SeqHeap[T]) Eq(other SeqHeap[T]) bool

Eq checks whether two heap sequences are equal.

func (SeqHeap[V]) Exclude added in v1.0.181

func (seq SeqHeap[V]) Exclude(fn func(V) bool) SeqHeap[V]

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(V) bool): The function to be applied to each element of the iterator to determine if it should be excluded from the result.

Returns:

- SeqHeap[V]: A new iterator containing the elements that do not satisfy the given condition.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
notEven := heap.Iter().
	Exclude(
		func(val int) bool {
			return val%2 == 0
		}).
	CollectWith(cmp.Cmp[int])

The resulting iterator will contain only the elements that do not satisfy the provided function.

func (SeqHeap[V]) Filter added in v1.0.181

func (seq SeqHeap[V]) Filter(fn func(V) bool) SeqHeap[V]

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(V) bool): The function to be applied to each element of the iterator to determine if it should be included in the result.

Returns:

- SeqHeap[V]: A new iterator containing the elements that satisfy the given condition.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
even := heap.Iter().
	Filter(
		func(val int) bool {
			return val%2 == 0
		}).
	CollectWith(cmp.Cmp[int])

The resulting iterator will contain only the elements that satisfy the provided function.

func (SeqHeap[V]) FilterMap added in v1.0.184

func (seq SeqHeap[V]) FilterMap(fn func(V) Option[V]) SeqHeap[V]

FilterMap applies a function to each element and filters out None results.

The function transforms and filters elements in a single pass. Elements where the function returns None are filtered out, and elements where it returns Some are unwrapped and included in the result.

Params:

  • fn (func(V) Option[V]): The function that transforms and filters elements. Returns Some(value) to include the transformed element, or None to filter it out.

Returns:

- SeqHeap[V]: A sequence containing only the successfully transformed elements.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
result := heap.Iter().FilterMap(func(n int) g.Option[int] {
	if n%2 == 0 {
		return g.Some(n * 10)
	}
	return g.None[int]()
}).CollectWith(cmp.Cmp[int])
// result contains only even numbers multiplied by 10

func (SeqHeap[V]) Find added in v1.0.181

func (seq SeqHeap[V]) Find(fn func(v V) bool) Option[V]

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(V) 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:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
found := heap.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 (SeqHeap[V]) First added in v1.0.191

func (seq SeqHeap[V]) First() Option[V]

First returns the first element from the sequence.

func (SeqHeap[V]) FlatMap added in v1.0.184

func (seq SeqHeap[V]) FlatMap(fn func(V) SeqHeap[V]) SeqHeap[V]

FlatMap applies a function to each element and flattens the results into a single sequence.

The function transforms each element into a new SeqHeap and then flattens all resulting sequences into a single sequence.

Params:

  • fn (func(V) SeqHeap[V]): The function that transforms each element into a SeqHeap.

Returns:

- SeqHeap[V]: A flattened sequence containing all elements from the transformed sequences.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3)
result := heap.Iter().FlatMap(func(n int) g.SeqHeap[int] {
	subHeap := g.NewHeap(cmp.Cmp[int])
	subHeap.Push(n, n*10)
	return subHeap.Iter()
}).CollectWith(cmp.Cmp[int])
// result contains: 1, 10, 2, 20, 3, 30 (order depends on heap implementation)

func (SeqHeap[V]) Flatten added in v1.0.181

func (seq SeqHeap[V]) Flatten() SeqHeap[V]

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:

- SeqHeap[V]: A single iterator containing elements from the sequence of iterators.

Example usage:

heap := g.NewHeap(cmp.Cmp[any])
heap.Push(
	1,
	g.SliceOf(2, 3),
	"abc",
	g.SliceOf("def", "ghi"),
	g.SliceOf(4.5, 6.7),
)

heap.Iter().Flatten().ForEach(func(v any) { fmt.Print(v, " ") })

Output: 1 2 3 abc def ghi 4.5 6.7

The resulting iterator will contain elements from each iterator in sequence.

func (SeqHeap[V]) Fold added in v1.0.181

func (seq SeqHeap[V]) Fold(init V, fn func(acc, val V) V) V

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 V.

Returns:

- T: The accumulated value after applying the function to all elements.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
sum := heap.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 (SeqHeap[V]) ForEach added in v1.0.181

func (seq SeqHeap[V]) ForEach(fn func(v V))

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(V)): The function to apply to each element.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
heap.Iter().ForEach(func(val int) {
    fmt.Println(val) // Replace this with the function logic you need.
})

The provided function will be applied to each element in the iterator.

func (SeqHeap[V]) GroupBy added in v1.0.181

func (seq SeqHeap[V]) GroupBy(fn func(a, b V) bool) SeqSlices[V]

GroupBy groups consecutive elements of the sequence based on a custom equality function.

The provided function `fn` takes two consecutive elements `a` and `b` and returns `true` if they belong to the same group, or `false` if a new group should start. The function returns a `SeqSlices[V]`, where each `[]V` represents a group of consecutive elements that satisfy the provided equality condition.

Notes:

  • Each group is returned as a copy of the elements, since `SeqHeap` does not guarantee that elements share the same backing array.

Parameters:

  • fn (func(a, b V) bool): Function that determines whether two consecutive elements belong to the same group.

Returns:

  • SeqSlices[V]: An iterator yielding slices, each containing one group.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 1, 2, 3, 2, 3, 4)
groups := heap.Iter().GroupBy(func(a, b int) bool { return a <= b }).Collect()
// Output: [Slice[1, 1, 2, 3] Slice[2, 3, 4]]

The resulting iterator will yield groups of consecutive elements according to the provided function.

func (SeqHeap[V]) Inspect added in v1.0.181

func (seq SeqHeap[V]) Inspect(fn func(v V)) SeqHeap[V]

Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.

func (SeqHeap[V]) Intersperse added in v1.0.181

func (seq SeqHeap[V]) Intersperse(sep V) SeqHeap[V]

Intersperse inserts the provided separator between elements of the iterator.

The function creates a new iterator that inserts the given separator between each consecutive pair of elements in the original iterator.

Params:

- sep (V): The separator to intersperse between elements.

Returns:

- SeqHeap[V]: An iterator containing elements with the separator interspersed.

Example usage:

heap := g.NewHeap(cmp.Cmp[string])
heap.Push("Hello", "World", "!")
heap.Iter().
	Intersperse(" ").
	ForEach(func(s string) { fmt.Print(s) })

Output: "! Hello World".

The resulting iterator will contain elements with the separator interspersed.

func (SeqHeap[V]) Last added in v1.0.191

func (seq SeqHeap[V]) Last() Option[V]

Last returns the last element from the sequence.

func (SeqHeap[V]) Map added in v1.0.181

func (seq SeqHeap[V]) Map(transform func(V) V) SeqHeap[V]

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(V) V): The function used to transform elements.

Returns:

- SeqHeap[V]: A iterator containing elements transformed by the provided function.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3)
doubled := heap.
	Iter().
	Map(
		func(val int) int {
			return val * 2
		}).
	CollectWith(cmp.Cmp[int])

The resulting iterator will contain elements transformed by the provided function.

func (SeqHeap[V]) MaxBy added in v1.0.181

func (seq SeqHeap[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]

MaxBy returns the maximum element in the sequence using the provided comparison function.

func (SeqHeap[V]) MinBy added in v1.0.181

func (seq SeqHeap[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]

MinBy returns the minimum element in the sequence using the provided comparison function.

func (*SeqHeap[V]) Next added in v1.0.189

func (seq *SeqHeap[V]) Next() Option[V]

Next extracts the next element from the iterator and advances it.

This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements.

Returns: - Option[V]: Some(value) if an element exists, None if the iterator is exhausted.

func (SeqHeap[V]) Nth added in v1.0.181

func (seq SeqHeap[V]) Nth(n Int) Option[V]

Nth returns the nth element (0-indexed) in the sequence.

func (SeqHeap[V]) Parallel added in v1.0.183

func (seq SeqHeap[V]) Parallel(workers ...Int) SeqHeapPar[V]

Parallel converts a sequential heap iterator into a parallel iterator with the specified number of workers. If no worker count is provided, it defaults to the number of CPU cores. The parallel iterator processes elements concurrently using a worker pool.

func (SeqHeap[V]) Partition added in v1.0.181

func (seq SeqHeap[V]) Partition(fn func(v V) bool, leftCmp, rightCmp func(V, V) cmp.Ordering) (*Heap[V], *Heap[V])

Partition divides the elements of the iterator into two separate heaps with custom comparison functions.

func (SeqHeap[V]) Permutations added in v1.0.181

func (seq SeqHeap[V]) Permutations() SeqSlices[V]

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:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3)
perms := heap.Iter().Permutations().Collect()
for _, perm := range perms {
    fmt.Println(perm)
}

Output: Slice[1, 2, 3] Slice[2, 1, 3] Slice[3, 1, 2] Slice[1, 3, 2] Slice[2, 3, 1] Slice[3, 2, 1]

The resulting iterator will contain iterators representing all possible permutations of the elements in the original iterator.

func (SeqHeap[V]) Pull added in v1.0.181

func (seq SeqHeap[V]) Pull() (func() (V, bool), func())

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 (SeqHeap[V]) Range added in v1.0.181

func (seq SeqHeap[V]) Range(fn func(v V) bool)

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(V) bool): The function that evaluates elements for continuation of iteration.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
heap.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 (SeqHeap[V]) Reduce added in v1.0.181

func (seq SeqHeap[V]) Reduce(fn func(a, b V) V) Option[V]

Reduce aggregates elements of the sequence using the provided function. The first element of the sequence is used as the initial accumulator value. If the sequence is empty, it returns None[V].

Params:

  • fn (func(V, V) V): Function that combines two values into one.

Returns:

  • Option[V]: The accumulated value wrapped in Some, or None if the sequence is empty.

Example:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
product := heap.Iter().Reduce(func(a, b int) int { return a * b })
if product.IsSome() {
    fmt.Println(product.Some()) // 120
} else {
    fmt.Println("empty")
}

func (SeqHeap[V]) Scan added in v1.0.184

func (seq SeqHeap[V]) Scan(init V, fn func(acc, val V) V) SeqHeap[V]

Scan applies a function to each element and produces a sequence of successive accumulated results.

The function takes an initial value and applies the provided function to each element along with the accumulated value, producing a new sequence where each element is the result of the accumulation. The initial value is included as the first element.

Params:

  • init (V): The initial value for the accumulation.
  • fn (func(acc, val V) V): The function that combines the accumulator with each element.

Returns:

- SeqHeap[V]: A sequence containing the initial value and all accumulated results.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
result := heap.Iter().Scan(0, func(acc, val int) int {
	return acc + val
}).CollectWith(cmp.Cmp[int])
// result contains: 0, plus cumulative sums of heap elements

func (SeqHeap[V]) Skip added in v1.0.181

func (seq SeqHeap[V]) Skip(n uint) SeqHeap[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:

- SeqHeap[V]: An iterator that starts after skipping the first n elements.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5, 6)
heap.Iter().Skip(3).ForEach(func(v int) { fmt.Print(v, " ") })

Output: 4 5 6

The resulting iterator will start after skipping the specified number of elements.

func (SeqHeap[V]) SortBy added in v1.0.181

func (seq SeqHeap[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqHeap[V]

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 V, and return the ordering between them.

Example:

heap := g.NewHeap(cmp.Cmp[string])
heap.Push("a", "c", "b")
heap.Iter().
	SortBy(func(a, b string) cmp.Ordering { return cmp.Cmp(b, a) }).
	ForEach(func(s string) { fmt.Print(s, " ") })

Output: c b a

The returned iterator is of type SeqHeap[V], which implements the iterator interface for further iteration over the sorted elements.

func (SeqHeap[V]) StepBy added in v1.0.181

func (seq SeqHeap[V]) StepBy(n uint) SeqHeap[V]

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: - SeqHeap[V]: A new iterator that produces elements from the original iterator with a step size of N.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
heap.Iter().StepBy(3).ForEach(func(v int) { fmt.Print(v, " ") })

Output: 1 4 7 10

The resulting iterator will produce elements from the original iterator with a step size of N.

func (SeqHeap[V]) Take added in v1.0.181

func (seq SeqHeap[V]) Take(n uint) SeqHeap[V]

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 (SeqHeap[V]) ToChan added in v1.0.181

func (seq SeqHeap[V]) ToChan(ctxs ...context.Context) chan V

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:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3)
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure cancellation to avoid goroutine leaks.
ch := heap.Iter().ToChan(ctx)
for val := range ch {
    fmt.Println(val)
}

The resulting channel allows streaming elements from the iterator with optional context handling.

func (SeqHeap[V]) Unique added in v1.0.181

func (seq SeqHeap[V]) Unique() SeqHeap[V]

Unique returns an iterator with only unique elements.

The function returns an iterator containing only the unique elements from the original iterator.

Returns:

- SeqHeap[V]: An iterator containing unique elements from the original iterator.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 2, 4, 5, 3)
heap.Iter().Unique().ForEach(func(v int) { fmt.Print(v, " ") })

Output: 1 2 3 4 5

The resulting iterator will contain only unique elements from the original iterator.

func (SeqHeap[V]) Windows added in v1.0.181

func (seq SeqHeap[V]) Windows(n Int) SeqSlices[V]

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:

- n (int): The size of each window.

Returns:

- SeqSlices[V]: An iterator yielding sliding windows of elements of the specified size.

Example usage:

heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5, 6)
windows := heap.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 (SeqHeap[V]) Zip added in v1.0.181

func (seq SeqHeap[V]) Zip(two SeqHeap[V]) SeqMapOrd[any, any]

Zip combines elements from the current sequence and another sequence into pairs, creating an ordered map with identical keys and values of type V.

type SeqHeapPar added in v1.0.183

type SeqHeapPar[V any] struct {
	// contains filtered or unexported fields
}

SeqHeapPar is a parallel iterator over a heap of elements of type T. It uses a fixed-size pool of worker goroutines to process elements concurrently.

func (SeqHeapPar[V]) All added in v1.0.183

func (p SeqHeapPar[V]) All(fn func(V) bool) bool

All returns true only if fn returns true for every element. It stops early on the first false.

func (SeqHeapPar[V]) Any added in v1.0.183

func (p SeqHeapPar[V]) Any(fn func(V) bool) bool

Any returns true if fn returns true for any element. It stops early on the first true.

func (SeqHeapPar[V]) Chain added in v1.0.183

func (p SeqHeapPar[V]) Chain(others ...SeqHeapPar[V]) SeqHeapPar[V]

Chain concatenates this SeqHeapPar with others, preserving full parallelism. Each sequence runs with its own worker pool in parallel.

func (SeqHeapPar[V]) Collect added in v1.0.183

func (p SeqHeapPar[V]) Collect(compareFn func(V, V) cmp.Ordering) *Heap[V]

Collect gathers all processed elements into a Heap with a custom comparison function.

func (SeqHeapPar[V]) Count added in v1.0.183

func (p SeqHeapPar[V]) Count() Int

Count returns the total number of elements processed.

func (SeqHeapPar[V]) Exclude added in v1.0.183

func (p SeqHeapPar[V]) Exclude(fn func(V) bool) SeqHeapPar[V]

Exclude removes elements for which fn returns true, in parallel.

func (SeqHeapPar[V]) Filter added in v1.0.183

func (p SeqHeapPar[V]) Filter(fn func(V) bool) SeqHeapPar[V]

Filter retains only elements where fn returns true.

func (SeqHeapPar[V]) FilterMap added in v1.0.184

func (p SeqHeapPar[V]) FilterMap(fn func(V) Option[V]) SeqHeapPar[V]

FilterMap applies fn to each element in parallel, keeping only Some values.

func (SeqHeapPar[V]) Find added in v1.0.183

func (p SeqHeapPar[V]) Find(fn func(V) bool) Option[V]

Find returns the first element satisfying fn, or None if no such element exists.

func (SeqHeapPar[V]) FlatMap added in v1.0.184

func (p SeqHeapPar[V]) FlatMap(fn func(V) SeqHeap[V]) SeqHeapPar[V]

FlatMap applies fn to each element in parallel, flattening the resulting sequences.

func (SeqHeapPar[V]) Flatten added in v1.0.183

func (p SeqHeapPar[V]) Flatten() SeqHeapPar[V]

Flatten unpacks nested slices or arrays in the source, returning a flat parallel sequence.

func (SeqHeapPar[V]) Fold added in v1.0.183

func (p SeqHeapPar[V]) Fold(init V, fn func(acc, v V) V) V

Fold reduces all elements into a single value, using fn to accumulate results. Note: This collects all processed elements first, then folds sequentially. The parallel processing happens during the Range phase.

func (SeqHeapPar[V]) ForEach added in v1.0.183

func (p SeqHeapPar[V]) ForEach(fn func(V))

ForEach applies fn to each element without early exit.

func (SeqHeapPar[V]) Inspect added in v1.0.183

func (p SeqHeapPar[V]) Inspect(fn func(V)) SeqHeapPar[V]

Inspect invokes fn on each element without altering the resulting sequence.

func (SeqHeapPar[V]) Map added in v1.0.183

func (p SeqHeapPar[V]) Map(fn func(V) V) SeqHeapPar[V]

Map applies fn to each element.

func (SeqHeapPar[V]) MaxBy added in v1.0.184

func (p SeqHeapPar[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]

MaxBy returns the maximum element according to the comparison function.

func (SeqHeapPar[V]) MinBy added in v1.0.184

func (p SeqHeapPar[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]

MinBy returns the minimum element according to the comparison function.

func (SeqHeapPar[V]) Partition added in v1.0.183

func (p SeqHeapPar[V]) Partition(fn func(V) bool, leftCmp, rightCmp func(V, V) cmp.Ordering) (*Heap[V], *Heap[V])

Partition partitions elements using custom comparison functions for each heap.

func (SeqHeapPar[V]) Range added in v1.0.183

func (p SeqHeapPar[V]) Range(fn func(V) bool)

Range applies fn to each processed element in parallel, stopping on false.

func (SeqHeapPar[V]) Reduce added in v1.0.183

func (p SeqHeapPar[V]) Reduce(fn func(a, b V) V) Option[V]

Reduce aggregates elements of the parallel sequence using the provided function. The first received element is used as the initial accumulator. If the sequence is empty, returns None[V]. Note: This collects all processed elements first, then reduces sequentially. The parallel processing happens during the Range phase.

func (SeqHeapPar[V]) Skip added in v1.0.183

func (p SeqHeapPar[V]) Skip(n uint) SeqHeapPar[V]

func (SeqHeapPar[V]) StepBy added in v1.0.184

func (p SeqHeapPar[V]) StepBy(n uint) SeqHeapPar[V]

StepBy yields every nth element.

func (SeqHeapPar[V]) Take added in v1.0.183

func (p SeqHeapPar[V]) Take(n uint) SeqHeapPar[V]

func (SeqHeapPar[V]) Unique added in v1.0.183

func (p SeqHeapPar[V]) Unique() SeqHeapPar[V]

Unique removes duplicate elements, preserving the first occurrence.

type SeqMap added in v1.0.63

type SeqMap[K comparable, V any] iter.Seq2[K, V]

SeqMap is an iterator over sequences of pairs of values, most commonly key-value pairs.

func (SeqMap[K, V]) Chain added in v1.0.63

func (seq SeqMap[K, V]) Chain(seqs ...SeqMap[K, V]) SeqMap[K, V]

Chain creates a new iterator by concatenating the current iterator with other iterators.

The function concatenates the key-value pairs from the current iterator with the key-value pairs from the provided iterators, producing a new iterator containing all concatenated elements.

Params:

- seqs ([]SeqMap[K, V]): Other iterators to be concatenated with the current iterator.

Returns:

- SeqMap[K, V]: A new iterator containing elements from the current iterator and the provided iterators.

Example usage:

iter1 := g.NewMap[int, string]().Set(1, "a").Iter()
iter2 := g.NewMap[int, string]().Set(2, "b").Iter()

// Concatenating iterators and collecting the result.
iter1.Chain(iter2).Collect().Print()

Output: Map{1:a, 2:b} // The output order may vary as Map is not ordered.

The resulting iterator will contain elements from both iterators.

func (SeqMap[K, V]) Collect added in v1.0.63

func (seq SeqMap[K, V]) Collect() Map[K, V]

Collect collects all key-value pairs from the iterator and returns a Map.

func (SeqMap[K, V]) Context added in v1.0.181

func (seq SeqMap[K, V]) Context(ctx context.Context) SeqMap[K, V]

Context allows the iteration to be controlled with a context.Context.

func (SeqMap[K, V]) Count added in v1.0.63

func (seq SeqMap[K, V]) Count() Int

Count consumes the iterator, counting the number of iterations and returning it.

func (SeqMap[K, V]) Exclude added in v1.0.63

func (seq SeqMap[K, V]) Exclude(fn func(K, V) bool) SeqMap[K, V]

Exclude returns a new iterator excluding elements that satisfy the provided function.

This function creates a new iterator excluding key-value pairs for which the provided function returns true. It iterates through the current iterator, applying the function to each key-value pair. If the function returns true for a key-value pair, it will be excluded from the resulting iterator.

Params:

- fn (func(K, V) bool): The function applied to each key-value pair to determine exclusion.

Returns:

- SeqMap[K, V]: An iterator excluding elements that satisfy the given function.

Example usage:

m := g.NewMap[int, int]().
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5)

notEven := m.Iter().
	Exclude(
		func(k, v int) bool {
			return v%2 == 0
		}).
	Collect()
notEven.Print()

Output: Map{1:1, 3:3, 5:5} // The output order may vary as Map is not ordered.

The resulting iterator will exclude elements for which the function returns true.

func (SeqMap[K, V]) Filter added in v1.0.63

func (seq SeqMap[K, V]) Filter(fn func(K, V) bool) SeqMap[K, V]

Filter returns a new iterator containing only the elements that satisfy the provided function.

This function creates a new iterator containing key-value pairs for which the provided function returns true. It iterates through the current iterator, applying the function to each key-value pair. If the function returns true for a key-value pair, it will be included in the resulting iterator.

Params:

- fn (func(K, V) bool): The function applied to each key-value pair to determine inclusion.

Returns:

- SeqMap[K, V]: An iterator containing elements that satisfy the given function.

m := g.NewMap[int, int]().
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5)

even := m.Iter().
	Filter(
		func(k, v int) bool {
			return v%2 == 0
		}).
	Collect()
even.Print()

Output: Map{2:2, 4:4} // The output order may vary as Map is not ordered.

The resulting iterator will contain elements for which the function returns true.

func (SeqMap[K, V]) FilterMap added in v1.0.184

func (seq SeqMap[K, V]) FilterMap(fn func(K, V) Option[Pair[K, V]]) SeqMap[K, V]

FilterMap applies a function to each key-value pair and filters out None results.

The function transforms and filters pairs in a single pass. Pairs where the function returns None are filtered out, and pairs where it returns Some are unwrapped and included in the result.

Params:

  • fn (func(K, V) Option[Pair[K, V]]): The function that transforms and filters pairs. Returns Some(Pair{key, value}) to include the transformed pair, or None to filter it out.

Returns:

- SeqMap[K, V]: A sequence containing only the successfully transformed pairs.

Example usage:

configs := g.Map[string, string]{"host": "localhost", "port": "8080", "debug": "invalid"}
validConfigs := configs.Iter().FilterMap(func(k string, v string) Option[Pair[string, string]] {
	if k == "port" || k == "host" {
		return Some(Pair[string, string]{Key: k, Value: v + "_validated"})
	}
	return None[Pair[string, string]]()
})
// validConfigs will yield: {"host": "localhost_validated", "port": "8080_validated"}

users := g.Map[string, int]{"alice": 25, "bob": 17, "charlie": 30}
adults := users.Iter().FilterMap(func(name string, age int) Option[Pair[string, int]] {
	if age >= 18 {
		return Some(Pair[string, int]{Key: name, Value: age})
	}
	return None[Pair[string, int]]()
})
// adults will yield: {"alice": 25, "charlie": 30}

func (SeqMap[K, V]) Find added in v1.0.63

func (seq SeqMap[K, V]) Find(fn func(k K, v V) bool) Option[Pair[K, V]]

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(K, V) bool): The function used to test elements for a condition.

Returns:

- Option[K, V]: An Option containing the first element that satisfies the condition; None if not found.

Example usage:

m := g.NewMap[int, int]()
m.Set(1, 1)
f := m.Iter().Find(func(_ int, v int) bool { return v == 1 })
if f.IsSome() {
	print(f.Some().Key)
}

The resulting Option may contain the first element that satisfies the condition, or None if not found.

func (SeqMap[K, V]) ForEach added in v1.0.63

func (seq SeqMap[K, V]) ForEach(fn func(k K, v V))

ForEach iterates through all elements and applies the given function to each key-value pair.

This function traverses the entire iterator and applies the provided function to each key-value pair. It iterates through the current iterator, executing the function on each key-value pair.

Params:

- fn (func(K, V)): The function to be applied to each key-value pair in the iterator.

Example usage:

m := g.NewMap[int, int]().
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5)

mmap := m.Iter().
	Map(
		func(k, v int) (int, int) {
			return k * k, v * v
		}).
	Collect()

mmap.Print()

Output: Map{1:1, 4:4, 9:9, 16:16, 25:25} // The output order may vary as Map is not ordered.

The function fn will be executed for each key-value pair in the iterator.

func (SeqMap[K, V]) Inspect added in v1.0.63

func (seq SeqMap[K, V]) Inspect(fn func(k K, v V)) SeqMap[K, V]

Inspect creates a new iterator that wraps around the current iterator and allows inspecting each key-value pair as it passes through.

func (SeqMap[K, V]) Keys added in v1.0.63

func (seq SeqMap[K, V]) Keys() SeqSlice[K]

Keys returns an iterator containing all the keys in the ordered Map.

func (SeqMap[K, V]) Map added in v1.0.63

func (seq SeqMap[K, V]) Map(transform func(K, V) (K, V)) SeqMap[K, V]

Map creates a new iterator by applying the given function to each key-value pair.

This function generates a new iterator by traversing the current iterator and applying the provided function to each key-value pair. It transforms the key-value pairs according to the given function.

Params:

  • fn (func(K, V) (K, V)): The function to be applied to each key-value pair in the iterator. It takes a key-value pair and returns a new transformed key-value pair.

Returns:

- SeqMap[K, V]: A new iterator containing key-value pairs transformed by the provided function.

Example usage:

m := g.NewMap[int, int]().
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5)

mmap := m.Iter().
	Map(
		func(k, v int) (int, int) {
			return k * k, v * v
		}).
	Collect()

mmap.Print()

Output: Map{1:1, 4:4, 9:9, 16:16, 25:25} // The output order may vary as Map is not ordered.

The resulting iterator will contain key-value pairs transformed by the given function.

func (*SeqMap[K, V]) Next added in v1.0.189

func (seq *SeqMap[K, V]) Next() Option[Pair[K, V]]

Next extracts the next key-value pair from the iterator and advances it.

This method consumes the next key-value pair from the iterator and returns them wrapped in an Option. The iterator itself is modified to point to the remaining elements.

Returns: - Option[Pair[K, V]]: Some(Pair{Key, Value}) if a pair exists, None if the iterator is exhausted.

func (SeqMap[K, V]) Nth added in v1.0.181

func (seq SeqMap[K, V]) Nth(n Int) Option[Pair[K, V]]

Nth returns the nth key-value pair (0-indexed) in the sequence.

func (SeqMap[K, V]) Parallel added in v1.0.151

func (seq SeqMap[K, V]) Parallel(workers ...Int) SeqMapPar[K, V]

IterPar parallelizes the SeqMap using the specified number of workers.

func (SeqMap[K, V]) Pull added in v1.0.63

func (seq SeqMap[K, V]) Pull() (func() (K, V, bool), func())

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 pair in the sequence and a boolean indicating whether the pair is valid. When the sequence is over, next returns a pair of zero values 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 a pair of zero values 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 (SeqMap[K, V]) Range added in v1.0.63

func (seq SeqMap[K, V]) Range(fn func(k K, v V) bool)

The iteration will stop when the provided function returns false for an element.

func (SeqMap[K, V]) Take added in v1.0.63

func (seq SeqMap[K, V]) Take(n uint) SeqMap[K, V]

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 (SeqMap[K, V]) Values added in v1.0.63

func (seq SeqMap[K, V]) Values() SeqSlice[V]

Values returns an iterator containing all the values in the ordered Map.

type SeqMapOrd added in v1.0.63

type SeqMapOrd[K comparable, V any] iter.Seq2[K, V]

SeqMapOrd is an iterator over sequences of ordered pairs of values, most commonly ordered key-value pairs.

func (SeqMapOrd[K, V]) Chain added in v1.0.63

func (seq SeqMapOrd[K, V]) Chain(seqs ...SeqMapOrd[K, V]) SeqMapOrd[K, V]

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 ([]seqMapOrd[K, V]): Other iterators to be concatenated with the current iterator.

Returns:

- SeqMapOrd[K, V]: A new iterator containing elements from the current iterator and the provided iterators.

Example usage:

iter1 := g.NewMapOrd[int, string]()
iter1.Set(1, "a").Iter()

iter2 := g.NewMapOrd[int, string]()
iter2.Set(2, "b").Iter()

// Concatenating iterators and collecting the result.
iter1.Chain(iter2).Collect().Print()

Output: MapOrd{1:a, 2:b}

The resulting iterator will contain elements from both iterators in the specified order.

func (SeqMapOrd[K, V]) Collect added in v1.0.63

func (seq SeqMapOrd[K, V]) Collect() MapOrd[K, V]

Collect collects all key-value pairs from the iterator and returns a MapOrd.

func (SeqMapOrd[K, V]) Context added in v1.0.181

func (seq SeqMapOrd[K, V]) Context(ctx context.Context) SeqMapOrd[K, V]

Context allows the iteration to be controlled with a context.Context.

func (SeqMapOrd[K, V]) Count added in v1.0.63

func (seq SeqMapOrd[K, V]) Count() Int

Count consumes the iterator, counting the number of iterations and returning it.

func (SeqMapOrd[K, V]) Exclude added in v1.0.63

func (seq SeqMapOrd[K, V]) Exclude(fn func(K, V) bool) SeqMapOrd[K, V]

Exclude returns a new iterator excluding elements that satisfy the provided function.

The function creates a new iterator excluding elements from the current iterator for which the provided function returns true.

Params:

- fn (func(K, V) bool): The function used to determine exclusion criteria for elements.

Returns:

- SeqMapOrd[K, V]: A new iterator excluding elements that satisfy the given condition.

Example usage:

mo := g.NewMapOrd[int, int]()
mo.
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5)

notEven := mo.Iter().
	Exclude(
		func(k, v int) bool {
			return v%2 == 0
		}).
	Collect()
notEven.Print()

Output: MapOrd{1:1, 3:3, 5:5}

The resulting iterator will exclude elements based on the provided condition.

func (SeqMapOrd[K, V]) Filter added in v1.0.63

func (seq SeqMapOrd[K, V]) Filter(fn func(K, V) bool) SeqMapOrd[K, V]

Filter returns a new iterator containing only the elements that satisfy the provided function.

The function creates a new iterator including elements from the current iterator for which the provided function returns true.

Params:

- fn (func(K, V) bool): The function used to determine inclusion criteria for elements.

Returns:

- SeqMapOrd[K, V]: A new iterator containing elements that satisfy the given condition.

Example usage:

mo := g.NewMapOrd[int, int]()
mo.
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5)

even := mo.Iter().
	Filter(
		func(k, v int) bool {
			return v%2 == 0
		}).
	Collect()
even.Print()

Output: MapOrd{2:2, 4:4}

The resulting iterator will include elements based on the provided condition.

func (SeqMapOrd[K, V]) Find added in v1.0.63

func (seq SeqMapOrd[K, V]) Find(fn func(k K, v V) bool) Option[Pair[K, V]]

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(K, V) bool): The function used to test elements for a condition.

Returns:

- Option[K, V]: An Option containing the first element that satisfies the condition; None if not found.

Example usage:

m := g.NewMapOrd[int, int]()
m.Set(1, 1)
f := m.Iter().Find(func(_ int, v int) bool { return v == 1 })
if f.IsSome() {
	print(f.Some().Key)
}

The resulting Option may contain the first element that satisfies the condition, or None if not found.

func (SeqMapOrd[K, V]) First added in v1.0.191

func (seq SeqMapOrd[K, V]) First() Option[Pair[K, V]]

First returns the first key-value pair from the sequence.

func (SeqMapOrd[K, V]) ForEach added in v1.0.63

func (seq SeqMapOrd[K, V]) ForEach(fn func(k K, v V))

ForEach iterates through all elements and applies the given function to each key-value pair.

The function applies the provided function to each key-value pair in the iterator.

Params:

- fn (func(K, V)): The function to be applied to each key-value pair in the iterator.

Example usage:

iter := g.NewMapOrd[int, int]()
iter.
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5).
	Iter()

iter.ForEach(func(key K, val V) {
    // Process key-value pair
})

The provided function will be applied to each key-value pair in the iterator.

func (SeqMapOrd[K, V]) Inspect added in v1.0.63

func (seq SeqMapOrd[K, V]) Inspect(fn func(k K, v V)) SeqMapOrd[K, V]

Inspect creates a new iterator that wraps around the current iterator and allows inspecting each key-value pair as it passes through.

func (SeqMapOrd[K, V]) Keys added in v1.0.63

func (seq SeqMapOrd[K, V]) Keys() SeqSlice[K]

Keys returns an iterator containing all the keys in the ordered Map.

func (SeqMapOrd[K, V]) Last added in v1.0.191

func (seq SeqMapOrd[K, V]) Last() Option[Pair[K, V]]

Last returns the last key-value pair from the sequence.

func (SeqMapOrd[K, V]) Map added in v1.0.63

func (seq SeqMapOrd[K, V]) Map(transform func(K, V) (K, V)) SeqMapOrd[K, V]

Map creates a new iterator by applying the given function to each key-value pair.

The function creates a new iterator by applying the provided function to each key-value pair in the iterator.

Params:

- fn (func(K, V) (K, V)): The function used to transform each key-value pair in the iterator.

Returns:

- SeqMapOrd[K, V]: A new iterator containing transformed key-value pairs.

Example usage:

mo := g.NewMapOrd[int, int]()
mo.
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5)

momap := mo.Iter().
	Map(
		func(k, v int) (int, int) {
			return k * k, v * v
		}).
	Collect()

momap.Print()

Output: MapOrd{1:1, 4:4, 9:9, 16:16, 25:25}

The resulting iterator will contain transformed key-value pairs.

func (*SeqMapOrd[K, V]) Next added in v1.0.189

func (seq *SeqMapOrd[K, V]) Next() Option[Pair[K, V]]

Next extracts the next key-value pair from the iterator and advances it.

This method consumes the next key-value pair from the iterator and returns them wrapped in an Option. The iterator itself is modified to point to the remaining elements.

Returns: - Option[Pair[K, V]]: Some(Pair{Key, Value}) if a pair exists, None if the iterator is exhausted.

func (SeqMapOrd[K, V]) Nth added in v1.0.181

func (seq SeqMapOrd[K, V]) Nth(n Int) Option[Pair[K, V]]

Nth returns the nth key-value pair (0-indexed) in the sequence.

func (SeqMapOrd[K, V]) Pull added in v1.0.63

func (seq SeqMapOrd[K, V]) Pull() (func() (K, V, bool), func())

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 pair in the sequence and a boolean indicating whether the pair is valid. When the sequence is over, next returns a pair of zero values 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 a pair of zero values 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 (SeqMapOrd[K, V]) Range added in v1.0.63

func (seq SeqMapOrd[K, V]) Range(fn func(k K, v V) bool)

Range iterates through elements until the given function returns false.

The function iterates through the key-value pairs in the iterator, applying the provided function to each pair. It continues iterating until the function returns false.

Params:

- fn (func(K, V) bool): The function to be applied to each key-value pair in the iterator.

Example usage:

iter := g.NewMapOrd[int, int]()
iter.
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5).
	Iter()

iter.Range(func(k, v int) bool {
    fmt.Println(v) // Replace this with the function logic you need.
    return v < 5 // Replace this with the condition for continuing iteration.
})

The iteration will stop when the provided function returns false.

func (SeqMapOrd[K, V]) Skip added in v1.0.63

func (seq SeqMapOrd[K, V]) Skip(n uint) SeqMapOrd[K, V]
iter := g.NewMapOrd[int, string]()
iter.
	Set(1, "a").
	Set(2, "b").
	Set(3, "c").
	Set(4, "d").
	Iter()

// Skipping the first two elements and collecting the rest.
iter.Skip(2).Collect().Print()

Output: MapOrd{3:c, 4:d}

The resulting iterator will start after skipping the specified number of elements.

func (SeqMapOrd[K, V]) SortBy added in v1.0.63

func (seq SeqMapOrd[K, V]) SortBy(fn func(a, b Pair[K, V]) cmp.Ordering) SeqMapOrd[K, V]

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 Pair[K, V], and return true if 'a' should be ordered before 'b', and false otherwise.

Example:

m := g.NewMapOrd[g.Int, g.String]()
m.
	Set(6, "bb").
	Set(0, "dd").
	Set(1, "aa").
	Set(5, "xx").
	Set(2, "cc").
	Set(3, "ff").
	Set(4, "zz").
	Iter().
	SortBy(
		func(a, b g.Pair[g.Int, g.String]) cmp.Ordering {
			return a.Key.Cmp(b.Key)
			// return a.Value.Cmp(b.Value)
		}).
	Collect().
	Print()

Output: MapOrd{0:dd, 1:aa, 2:cc, 3:ff, 4:zz, 5:xx, 6:bb}

The returned iterator is of type SeqMapOrd[K, V], which implements the iterator interface for further iteration over the sorted elements.

func (SeqMapOrd[K, V]) SortByKey added in v1.0.73

func (seq SeqMapOrd[K, V]) SortByKey(fn func(a, b K) cmp.Ordering) SeqMapOrd[K, V]

SortByKey applies a custom sorting function to the keys 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 K, and return true if 'a' should be ordered before 'b', and false otherwise.

Example:

m := g.NewMapOrd[g.Int, g.String]()
m.
	Set(6, "bb").
	Set(0, "dd").
	Set(1, "aa").
	Set(5, "xx").
	Set(2, "cc").
	Set(3, "ff").
	Set(4, "zz").
	Iter().
	SortByKey(g.Int.Cmp).
	Collect().
	Print()

Output: MapOrd{0:dd, 1:aa, 2:cc, 3:ff, 4:zz, 5:xx, 6:bb}

func (SeqMapOrd[K, V]) SortByValue added in v1.0.73

func (seq SeqMapOrd[K, V]) SortByValue(fn func(a, b V) cmp.Ordering) SeqMapOrd[K, V]

SortByValue applies a custom sorting function to the values 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 V, and return true if 'a' should be ordered before 'b', and false otherwise.

Example:

m := g.NewMapOrd[g.Int, g.String]()
m.
	Set(6, "bb").
	Set(0, "dd").
	Set(1, "aa").
	Set(5, "xx").
	Set(2, "cc").
	Set(3, "ff").
	Set(4, "zz").
	Iter().
	SortByValue(g.String.Cmp).
	Collect().
	Print()

Output: MapOrd{1:aa, 6:bb, 2:cc, 0:dd, 3:ff, 5:xx, 4:zz}

func (SeqMapOrd[K, V]) StepBy added in v1.0.63

func (seq SeqMapOrd[K, V]) StepBy(n uint) SeqMapOrd[K, V]

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 int: The step size, indicating how many elements to skip between each iteration.

Returns: - SeqMapOrd[K, V]: A new iterator that produces key-value pairs from the original iterator with a step size of N.

Example usage:

mapIter := g.MapOrd[string, int]{{"one", 1}, {"two", 2}, {"three", 3}}.Iter()
iter := mapIter.StepBy(2)
result := iter.Collect()
result.Print()

Output: MapOrd{one:1, three:3}

The resulting iterator will produce key-value pairs from the original iterator with a step size of N.

func (SeqMapOrd[K, V]) Take added in v1.0.63

func (seq SeqMapOrd[K, V]) Take(n uint) SeqMapOrd[K, V]

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 (SeqMapOrd[K, V]) ToChan added in v1.0.69

func (seq SeqMapOrd[K, V]) ToChan(ctxs ...context.Context) chan Pair[K, V]

ToChan converts the iterator into a channel, optionally with context(s).

The function converts the key-value pairs from the iterator into a channel, allowing iterative processing using channels. It can be used to stream key-value pairs for concurrent or asynchronous operations.

Params:

- ctxs (...context.Context): Optional context(s) that can be used to cancel or set deadlines for the operation.

Returns:

- chan Pair[K, V]: A channel emitting key-value pairs from the iterator.

Example usage:

iter := g.NewMapOrd[int, int]()
iter.
	Set(1, 1).
	Set(2, 2).
	Set(3, 3).
	Set(4, 4).
	Set(5, 5).
	Iter()

ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure cancellation to avoid goroutine leaks.

ch := iter.ToChan(ctx)
for pair := range ch {
    // Process key-value pair from the channel
}

The function converts the iterator into a channel to allow sequential or concurrent processing of key-value pairs.

func (SeqMapOrd[K, V]) Unzip added in v1.0.63

func (seq SeqMapOrd[K, V]) Unzip() (SeqSlice[K], SeqSlice[V])

Unzip returns a tuple of slices containing keys and values from the ordered map.

func (SeqMapOrd[K, V]) Values added in v1.0.63

func (seq SeqMapOrd[K, V]) Values() SeqSlice[V]

Values returns an iterator containing all the values in the ordered Map.

type SeqMapPar added in v1.0.151

type SeqMapPar[K comparable, V any] struct {
	// contains filtered or unexported fields
}

SeqMapPar is the parallel version of SeqMap[K,V].

func (SeqMapPar[K, V]) All added in v1.0.151

func (p SeqMapPar[K, V]) All(fn func(K, V) bool) bool

All returns true if fn returns true for every pair.

func (SeqMapPar[K, V]) Any added in v1.0.151

func (p SeqMapPar[K, V]) Any(fn func(K, V) bool) bool

Any returns true if fn returns true for any pair.

func (SeqMapPar[K, V]) Chain added in v1.0.151

func (p SeqMapPar[K, V]) Chain(others ...SeqMapPar[K, V]) SeqMapPar[K, V]

Chain concatenates this SeqMapPar with others, preserving full parallelism. Each sequence runs with its own worker pool in parallel..

func (SeqMapPar[K, V]) Collect added in v1.0.151

func (p SeqMapPar[K, V]) Collect() Map[K, V]

Collect gathers all processed pairs into a Map.

func (SeqMapPar[K, V]) Count added in v1.0.151

func (p SeqMapPar[K, V]) Count() Int

Count returns the total number of processed pairs.

func (SeqMapPar[K, V]) Exclude added in v1.0.151

func (p SeqMapPar[K, V]) Exclude(fn func(K, V) bool) SeqMapPar[K, V]

Exclude removes pairs where fn returns true.

func (SeqMapPar[K, V]) Filter added in v1.0.151

func (p SeqMapPar[K, V]) Filter(fn func(K, V) bool) SeqMapPar[K, V]

Filter retains only pairs where fn returns true.

func (SeqMapPar[K, V]) Find added in v1.0.151

func (p SeqMapPar[K, V]) Find(fn func(K, V) bool) Option[Pair[K, V]]

Find returns the first pair matching fn, or a zero Option if none.

func (SeqMapPar[K, V]) ForEach added in v1.0.158

func (p SeqMapPar[K, V]) ForEach(fn func(K, V))

ForEach invokes fn on each key/value pair for side-effects, processing all pairs in parallel without early exit.

func (SeqMapPar[K, V]) Inspect added in v1.0.158

func (p SeqMapPar[K, V]) Inspect(fn func(K, V)) SeqMapPar[K, V]

Inspect invokes fn on each key/value pair for side-effects, without modifying the resulting sequence.

func (SeqMapPar[K, V]) Map added in v1.0.151

func (p SeqMapPar[K, V]) Map(transform func(K, V) (K, V)) SeqMapPar[K, V]

Map applies transform to each pair.

func (SeqMapPar[K, V]) Range added in v1.0.151

func (p SeqMapPar[K, V]) Range(fn func(K, V) bool)

Range applies fn to each processed pair in parallel, stopping early if fn returns false.

func (SeqMapPar[K, V]) Skip added in v1.0.151

func (p SeqMapPar[K, V]) Skip(n Int) SeqMapPar[K, V]

Skip drops the first n pairs.

func (SeqMapPar[K, V]) Take added in v1.0.151

func (p SeqMapPar[K, V]) Take(n Int) SeqMapPar[K, V]

Take yields at most n pairs.

type SeqResult added in v1.0.115

type SeqResult[V any] iter.Seq[Result[V]]

SeqResult is an iterator over sequences of Result[V] values.

func (SeqResult[V]) All added in v1.0.115

func (seq SeqResult[V]) All(fn func(v V) bool) Result[bool]

All checks whether all Ok values in the sequence satisfy the provided condition.

If an Err is encountered in the sequence, that Err is immediately returned. Otherwise, it returns Ok(true) if all Ok values satisfy the function, or Ok(false) if at least one does not.

func (SeqResult[V]) Any added in v1.0.115

func (seq SeqResult[V]) Any(fn func(v V) bool) Result[bool]

Any checks whether any Ok value in the sequence satisfies the provided condition.

If an Err is encountered, that Err is immediately returned. Otherwise, it returns Ok(true) if at least one Ok value satisfies the function, or Ok(false) if none do.

func (SeqResult[V]) Chain added in v1.0.115

func (seq SeqResult[V]) Chain(seqs ...SeqResult[V]) SeqResult[V]

Chain concatenates this sequence with other sequences, returning a new sequence of Result[V].

The function yields all elements (Ok or Err) from the current sequence, then from each of the provided sequences in order. If an Err is encountered, it is yielded immediately, ending further iteration.

func (SeqResult[V]) Collect added in v1.0.115

func (seq SeqResult[V]) Collect() Slice[Result[V]]

Collect gathers all Ok values from the iterator into a Slice. If any value is Err, the first such Err is returned immediately.

func (SeqResult[V]) Context added in v1.0.181

func (seq SeqResult[V]) Context(ctx context.Context) SeqResult[V]

Context allows the iteration to be controlled with a context.Context.

func (SeqResult[V]) Count added in v1.0.116

func (seq SeqResult[V]) Count() Int

Count consumes the entire sequence, counting how many times the yield function is invoked. Err elements do not stop the count but are still passed to the yield function (which returns false immediately, stopping iteration).

func (SeqResult[V]) Dedup added in v1.0.115

func (seq SeqResult[V]) Dedup() SeqResult[V]

Dedup removes consecutive duplicates of Ok values from the sequence, returning a new sequence.

If an Err is encountered, it is yielded immediately and iteration stops. Consecutive Ok duplicates (based on equality) are filtered out so only the first occurrence is yielded.

func (SeqResult[V]) Err added in v1.0.191

func (seq SeqResult[V]) Err() SeqSlice[error]

Err returns a new sequence containing only the error values from the original sequence. All Ok values are filtered out.

func (SeqResult[V]) Exclude added in v1.0.115

func (seq SeqResult[V]) Exclude(fn func(V) bool) SeqResult[V]

Exclude returns a new sequence that excludes Ok elements which satisfy the provided function.

If an Err is encountered, it is yielded as Err (and stops iteration). Only Ok elements for which 'fn' returns false are yielded downstream.

func (SeqResult[V]) Filter added in v1.0.115

func (seq SeqResult[V]) Filter(fn func(V) bool) SeqResult[V]

Filter returns a new sequence containing only the Ok elements that satisfy the provided function.

If an Err is encountered, it is yielded immediately as Err (and stops further iteration). Only Ok elements for which fn returns true are yielded downstream as Ok.

func (SeqResult[V]) Find added in v1.0.116

func (seq SeqResult[V]) Find(fn func(V) bool) Result[Option[V]]

Find searches the sequence for the first Ok value that satisfies the provided function.

If an Err is encountered, it returns that Err immediately. If a matching Ok value is found, iteration stops and we return Ok(Some(...)). If no matching Ok value is found, it returns Ok(None).

func (SeqResult[V]) First added in v1.0.191

func (seq SeqResult[V]) First() Result[Option[V]]

First returns the first Ok element from the sequence. If the sequence is empty or contains only Err values, None is returned. If an Err is encountered, that Err is returned.

func (SeqResult[V]) FirstErr added in v1.0.191

func (seq SeqResult[V]) FirstErr() Option[error]

FirstErr returns the first error encountered in the sequence. If no error is found, it returns None. The iteration stops at the first error.

func (SeqResult[V]) ForEach added in v1.0.115

func (seq SeqResult[V]) ForEach(fn func(v Result[V]))

ForEach applies a function to each Result in the sequence (Ok or Err) without modifying the sequence.

The iteration continues over all elements, passing them to fn for side effects.

func (SeqResult[V]) Inspect added in v1.0.115

func (seq SeqResult[V]) Inspect(fn func(v V)) SeqResult[V]

Inspect calls fn for every Ok value without changing it. An Err immediately stops iteration by returning false.

func (SeqResult[V]) Intersperse added in v1.0.115

func (seq SeqResult[V]) Intersperse(sep V) SeqResult[V]

Intersperse inserts the provided Ok separator between each Ok element of the sequence.

If an Err is encountered, it is yielded as Err and iteration stops immediately. For Ok elements, after the first yield, a separator is inserted before each subsequent Ok value.

func (SeqResult[V]) Last added in v1.0.191

func (seq SeqResult[V]) Last() Result[Option[V]]

Last returns the last Ok element from the sequence. If the sequence is empty or contains only Err values, None is returned. If an Err is encountered, that Err is returned.

func (SeqResult[V]) Map added in v1.0.115

func (seq SeqResult[V]) Map(transform func(V) V) SeqResult[V]

Map transforms each Ok value in the sequence using the given function, returning a new sequence of Result.

If an Err is encountered, it is passed downstream as-is and ends the iteration (yield returns false).

func (*SeqResult[V]) Next added in v1.0.189

func (seq *SeqResult[V]) Next() Option[Result[V]]

Next extracts the next element from the iterator and advances it.

This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements.

Returns: - Option[Result[V]]: Some(Result[V]) if an element exists, None if the iterator is exhausted.

func (SeqResult[V]) Nth added in v1.0.181

func (seq SeqResult[V]) Nth(n Int) Result[Option[V]]

Nth returns the nth Ok element (0-indexed) in the sequence. If an Err is encountered before reaching the nth element, that Err is returned. If there are fewer than n+1 Ok elements, None is returned.

func (SeqResult[V]) Ok added in v1.0.191

func (seq SeqResult[V]) Ok() SeqSlice[V]

Ok returns a new sequence containing only the Ok values from the original sequence. All Err values are filtered out.

func (SeqResult[V]) Partition added in v1.0.191

func (seq SeqResult[V]) Partition() (Slice[V], Slice[error])

Partition separates the sequence into two slices: one containing all Ok values and one containing all errors. The iteration continues through all elements, collecting each into the appropriate slice.

func (SeqResult[V]) Pull added in v1.0.115

func (seq SeqResult[V]) Pull() (func() (Result[V], bool), func())

Pull converts the “push-style” sequence of Result[V] into a “pull-style” iterator accessed by two functions: next and stop.

The next function returns the next Result[V] in the sequence and a boolean indicating whether the value is valid. When the sequence is over, next returns the zero value 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 value and false.

The stop function 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. It is valid to call stop multiple times and after next has already returned false.

It is an error to call next or stop from multiple goroutines simultaneously.

func (SeqResult[V]) Range added in v1.0.115

func (seq SeqResult[V]) Range(fn func(v Result[V]) bool)

Range iterates through elements until the given function returns false.

For each element (Ok or Err), fn is called. If fn returns false, iteration stops immediately.

func (SeqResult[V]) Skip added in v1.0.115

func (seq SeqResult[V]) Skip(n uint) SeqResult[V]

Skip returns a new sequence that skips the first n Ok elements.

If an Err is encountered, it is yielded as is and iteration stops. Once n Ok elements have been skipped, subsequent elements (Ok or Err) are yielded normally.

func (SeqResult[V]) StepBy added in v1.0.115

func (seq SeqResult[V]) StepBy(n uint) SeqResult[V]

StepBy creates a new sequence that yields every nth Ok element from the original sequence.

If an Err is encountered, it is yielded immediately and stops iteration. For Ok elements, only every n-th element is yielded.

func (SeqResult[V]) Take added in v1.0.115

func (seq SeqResult[V]) Take(n uint) SeqResult[V]

Take returns a new sequence with the first n Ok elements. If an Err is encountered, it is yielded immediately and iteration stops. After n Ok elements are yielded, the sequence ends.

func (SeqResult[V]) Unique added in v1.0.115

func (seq SeqResult[V]) Unique() SeqResult[V]

Unique returns a new sequence that contains only the first occurrence of each distinct Ok value.

If an Err is encountered, it is yielded immediately and iteration stops. Future occurrences of a previously seen Ok value are skipped.

type SeqSet added in v1.0.63

type SeqSet[V comparable] iter.Seq[V]

SeqSet is an iterator over sequences of unique values.

func (SeqSet[V]) Chain added in v1.0.63

func (seq SeqSet[V]) Chain(seqs ...SeqSet[V]) SeqSet[V]

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 ([]SeqSet[V]): Other iterators to be concatenated with the current iterator.

Returns:

- SeqSet[V]: A new iterator containing elements from the current iterator and the provided iterators.

Example usage:

iter1 := g.SetOf(1, 2, 3).Iter()
iter2 := g.SetOf(4, 5, 6).Iter()
iter1.Chain(iter2).Collect().Print()

Output: Set{3, 4, 5, 6, 1, 2} // The output order may vary as the Set type is not ordered.

The resulting iterator will contain elements from both iterators.

func (SeqSet[V]) Collect added in v1.0.63

func (seq SeqSet[V]) Collect() Set[V]

Collect gathers all elements from the iterator into a Set.

func (SeqSet[V]) Context added in v1.0.181

func (seq SeqSet[V]) Context(ctx context.Context) SeqSet[V]

Context allows the iteration to be controlled with a context.Context.

func (SeqSet[V]) Count added in v1.0.63

func (seq SeqSet[V]) Count() Int

Count consumes the iterator, counting the number of iterations and returning it.

func (SeqSet[V]) Exclude added in v1.0.63

func (seq SeqSet[V]) Exclude(fn func(V) bool) SeqSet[V]

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(V) bool): The function to be applied to each element of the iterator to determine if it should be excluded from the result.

Returns:

- SeqSet[V]: A new iterator containing the elements that do not satisfy the given condition.

Example usage:

set := g.SetOf(1, 2, 3, 4, 5)
notEven := set.Iter().
	Exclude(
		func(val int) bool {
			return val%2 == 0
		}).
	Collect()
notEven.Print()

Output: Set{1, 3, 5} // The output order may vary as the Set type is not ordered.

The resulting iterator will contain only the elements that do not satisfy the provided function.

func (SeqSet[V]) Filter added in v1.0.63

func (seq SeqSet[V]) Filter(fn func(V) bool) SeqSet[V]

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(V) bool): The function to be applied to each element of the iterator to determine if it should be included in the result.

Returns:

- SeqSet[V]: A new iterator containing the elements that satisfy the given condition.

Example usage:

set := g.SetOf(1, 2, 3, 4, 5)
even := set.Iter().
	Filter(
		func(val int) bool {
			return val%2 == 0
		}).
	Collect()
even.Print()

Output: Set{2, 4} // The output order may vary as the Set type is not ordered.

The resulting iterator will contain only the elements that satisfy the provided function.

func (SeqSet[V]) Find added in v1.0.114

func (seq SeqSet[V]) Find(fn func(v V) bool) Option[V]

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(V) 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.SetOf(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 (SeqSet[V]) ForEach added in v1.0.63

func (seq SeqSet[V]) ForEach(fn func(v V))

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(V)): The function to apply to each element.

Example usage:

iter := g.SetOf(1, 2, 3).Iter()
iter.ForEach(func(val V) {
    fmt.Println(val) // Replace this with the function logic you need.
})

The provided function will be applied to each element in the iterator.

func (SeqSet[V]) Inspect added in v1.0.63

func (seq SeqSet[V]) Inspect(fn func(v V)) SeqSet[V]

Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.

func (SeqSet[V]) Map added in v1.0.63

func (seq SeqSet[V]) Map(transform func(V) V) SeqSet[V]

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(V) V): The function used to transform elements.

Returns:

- SeqSet[V]: A new iterator containing elements transformed by the provided function.

Example usage:

set := g.SetOf(1, 2, 3)
doubled := set.Iter().
	Map(
		func(val int) int {
			return val * 2
		}).
	Collect()
doubled.Print()

Output: Set{2, 4, 6} // The output order may vary as the Set type is not ordered.

The resulting iterator will contain elements transformed by the provided function.

func (*SeqSet[V]) Next added in v1.0.189

func (seq *SeqSet[V]) Next() Option[V]

Next extracts the next element from the iterator and advances it.

This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements.

Returns: - Option[V]: Some(value) if an element exists, None if the iterator is exhausted.

func (SeqSet[V]) Nth added in v1.0.181

func (seq SeqSet[V]) Nth(n Int) Option[V]

Nth returns the nth element (0-indexed) in the sequence.

func (SeqSet[V]) Pull added in v1.0.63

func (seq SeqSet[V]) Pull() (func() (V, bool), func())

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 (SeqSet[V]) Range added in v1.0.63

func (seq SeqSet[V]) Range(fn func(v V) bool)

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. The iteration will stop when the provided function returns false for an element.

Params: - fn (func(V) bool): The function that evaluates elements for continuation of iteration.

Example usage:

iter := g.SetOf(1, 2, 2, 3, 4, 5).Iter()

iter.Range(func(v int) bool {
    if v == 3 {
        return false
    }
    print(v)
    return true
})

func (SeqSet[V]) Take added in v1.0.181

func (seq SeqSet[V]) Take(n uint) SeqSet[V]

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.

type SeqSlice added in v1.0.63

type SeqSlice[V any] iter.Seq[V]

SeqSlice is an iterator over sequences of individual values.

func FromChan added in v1.0.69

func FromChan[V any](ch <-chan V) SeqSlice[V]

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 Range added in v1.0.156

func Range[T constraints.Integer](start, stop T, step ...T) SeqSlice[T]

Range returns a SeqSlice[T] yielding a sequence of integers of type T, starting at start, incrementing by step, and ending before stop (exclusive).

  • If step is omitted, it defaults to 1.
  • If step is 0, the sequence is empty.
  • If step does not move toward stop (e.g., positive step with start > stop), the sequence is empty.

Examples:

  • Range(0, 5) yields [0, 1, 2, 3, 4]
  • Range(5, 0, -1) yields [5, 4, 3, 2, 1]

func RangeInclusive added in v1.0.176

func RangeInclusive[T constraints.Integer](start, stop T, step ...T) SeqSlice[T]

RangeInclusive returns a SeqSlice[T] yielding a sequence of integers of type T, starting at start, incrementing by step, and ending at stop (inclusive).

  • If step is omitted, it defaults to 1.
  • If step is 0, the sequence is empty.
  • If step does not move toward stop (e.g., positive step with start > stop), the sequence is empty.

Examples:

  • RangeInclusive(0, 5) yields [0, 1, 2, 3, 4, 5]
  • RangeInclusive(5, 0, -1) yields [5, 4, 3, 2, 1, 0]

func (SeqSlice[V]) All added in v1.0.63

func (seq SeqSlice[V]) All(fn func(v V) bool) bool

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(V) 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 (SeqSlice[V]) Any added in v1.0.63

func (seq SeqSlice[V]) Any(fn func(V) bool) bool

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(V) 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 (SeqSlice[V]) Chain added in v1.0.63

func (seq SeqSlice[V]) Chain(seqs ...SeqSlice[V]) SeqSlice[V]

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 (SeqSlice[V]) Chunks added in v1.0.63

func (seq SeqSlice[V]) Chunks(n Int) SeqSlices[V]

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 (SeqSlice[V]) Collect added in v1.0.63

func (seq SeqSlice[V]) Collect() Slice[V]

Collect gathers all elements from the iterator into a Slice.

func (SeqSlice[V]) Combinations added in v1.0.63

func (seq SeqSlice[V]) Combinations(size Int) SeqSlices[V]

Combinations generates all combinations of length 'n' from the sequence.

func (SeqSlice[V]) Context added in v1.0.181

func (seq SeqSlice[V]) Context(ctx context.Context) SeqSlice[V]

Context allows the iteration to be controlled with a context.Context.

func (SeqSlice[V]) Count added in v1.0.63

func (seq SeqSlice[V]) Count() Int

Count consumes the iterator, counting the number of iterations and returning it.

func (SeqSlice[V]) Counter added in v1.0.67

func (seq SeqSlice[V]) Counter() SeqMapOrd[any, Int]

Counter returns a map where each key is a unique element from the slice and each value is the count of how many times that element appears.

The function counts the occurrences of each element in the slice and returns a map representing the unique elements and their respective counts. This method uses iter.Counter from the iter package.

Returns:

- map[any]Int: 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()
// The counts map will contain:
// 1 -> 3 (since 1 appears three times)
// 2 -> 2 (since 2 appears two times)
// 3 -> 1 (since 3 appears once)

func (SeqSlice[V]) Cycle added in v1.0.63

func (seq SeqSlice[V]) Cycle() SeqSlice[V]

Cycle returns an iterator that endlessly repeats the elements of the current sequence.

func (SeqSlice[V]) Dedup added in v1.0.63

func (seq SeqSlice[V]) Dedup() SeqSlice[V]

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 (SeqSlice[V]) Enumerate added in v1.0.63

func (seq SeqSlice[V]) Enumerate() SeqMapOrd[Int, V]

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 (SeqSlice[V]) Exclude added in v1.0.63

func (seq SeqSlice[V]) Exclude(fn func(V) bool) SeqSlice[V]

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(V) 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 (SeqSlice[V]) Filter added in v1.0.63

func (seq SeqSlice[V]) Filter(fn func(V) bool) SeqSlice[V]

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(V) 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 (SeqSlice[V]) FilterMap added in v1.0.184

func (seq SeqSlice[V]) FilterMap(fn func(V) Option[V]) SeqSlice[V]

FilterMap applies a function to each element and filters out None results.

The function transforms and filters in a single pass. Elements where the function returns None are filtered out, and elements where it returns Some are unwrapped and included in the result.

Params:

  • fn (func(V) Option[V]): The function that transforms and filters elements. Returns Some(value) to include the transformed value, or None to filter it out.

Returns:

- SeqSlice[V]: A sequence containing only the successfully transformed elements.

Example usage:

strings := g.Slice[string]{"1", "2", "abc", "3", "xyz"}.Iter()
numbers := strings.FilterMap(func(s string) Option[int] {
	if n, err := strconv.Atoi(s); err == nil {
		return Some(n)
	}
	return None[int]()
})
// numbers will yield: 1, 2, 3

values := g.Slice[int]{1, -2, 3, -4, 5}.Iter()
positiveDoubled := values.FilterMap(func(n int) Option[int] {
	if n > 0 {
		return Some(n * 2)
	}
	return None[int]()
})
// positiveDoubled will yield: 2, 6, 10

func (SeqSlice[V]) Find added in v1.0.63

func (seq SeqSlice[V]) Find(fn func(v V) bool) Option[V]

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(V) 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 (SeqSlice[V]) First added in v1.0.191

func (seq SeqSlice[V]) First() Option[V]

First returns the first element from the sequence.

func (SeqSlice[V]) FlatMap added in v1.0.184

func (seq SeqSlice[V]) FlatMap(fn func(V) SeqSlice[V]) SeqSlice[V]

FlatMap applies a function to each element that returns an iterator, then flattens the results.

The function transforms each element into a sequence and then concatenates all sequences into a single flat sequence.

Params:

- fn (func(V) SeqSlice[V]): The function that transforms each element into a sequence.

Returns:

- SeqSlice[V]: A flattened sequence containing all elements from the transformed sequences.

Example usage:

words := g.Slice[string]{"hello world", "foo bar"}.Iter()
chars := words.FlatMap(func(s string) SeqSlice[string] {
	return g.String(s).Split("")
})
// chars will yield: "h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "f", "o", "o", " ", "b", "a", "r"

numbers := g.Slice[int]{1, 2, 3}.Iter()
expanded := numbers.FlatMap(func(n int) SeqSlice[int] {
	return g.Slice[int]{n, n*10, n*100}.Iter()
})
// expanded will yield: 1, 10, 100, 2, 20, 200, 3, 30, 300

func (SeqSlice[V]) Flatten added in v1.0.63

func (seq SeqSlice[V]) Flatten() SeqSlice[V]

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 (SeqSlice[V]) Fold added in v1.0.63

func (seq SeqSlice[V]) Fold(init V, fn func(acc, val V) V) V

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 V.

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 (SeqSlice[V]) ForEach added in v1.0.63

func (seq SeqSlice[V]) ForEach(fn func(v V))

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(V)): The function to apply to each element.

Example usage:

iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
iter.ForEach(func(val V) {
    fmt.Println(val) // Replace this with the function logic you need.
})

The provided function will be applied to each element in the iterator.

func (SeqSlice[V]) GroupBy added in v1.0.178

func (seq SeqSlice[V]) GroupBy(fn func(a, b V) bool) SeqSlices[V]

GroupBy groups consecutive elements of the sequence based on a custom equality function.

The provided function `fn` takes two consecutive elements `a` and `b` and returns `true` if they belong to the same group, or `false` if a new group should start. The function returns a `SeqSlices[V]`, where each `[]V` represents a group of consecutive elements that satisfy the provided equality condition.

Notes:

  • Each group is returned as a copy of the elements, since `SeqSlice` does not guarantee that elements share the same backing array.

Parameters:

  • fn (func(a, b V) bool): Function that determines whether two consecutive elements belong to the same group.

Returns:

  • SeqSlices[V]: An iterator yielding slices, each containing one group.

Example usage:

slice := g.SliceOf(1, 1, 2, 3, 2, 3, 4)
groups := slice.Iter().GroupBy(func(a, b int) bool { return a <= b }).Collect()
// Output: [Slice[1, 1, 2, 3] Slice[2, 3, 4]]

The resulting iterator will yield groups of consecutive elements according to the provided function.

func (SeqSlice[V]) Inspect added in v1.0.63

func (seq SeqSlice[V]) Inspect(fn func(v V)) SeqSlice[V]

Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.

func (SeqSlice[V]) Intersperse added in v1.0.80

func (seq SeqSlice[V]) Intersperse(sep V) SeqSlice[V]

Intersperse inserts the provided separator between elements of the iterator.

The function creates a new iterator that inserts the given separator between each consecutive pair of elements in the original iterator.

Params:

- sep (V): The separator to intersperse between elements.

Returns:

- SeqSlice[V]: An iterator containing elements with the separator interspersed.

Example usage:

g.Slice[string]{"Hello", "World", "!"}.
	Iter().
	Intersperse(" ").
	Collect().
	Join().
	Print()

Output: "Hello World !".

The resulting iterator will contain elements with the separator interspersed.

func (SeqSlice[V]) Last added in v1.0.191

func (seq SeqSlice[V]) Last() Option[V]

Last returns the last element from the sequence.

func (SeqSlice[V]) Map added in v1.0.63

func (seq SeqSlice[V]) Map(transform func(V) V) SeqSlice[V]

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(V) V): 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 (SeqSlice[V]) MaxBy added in v1.0.181

func (seq SeqSlice[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]

MaxBy returns the maximum element in the sequence using the provided comparison function.

func (SeqSlice[V]) MinBy added in v1.0.181

func (seq SeqSlice[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]

Min returns the minimum element in the sequence using the provided comparison function.

func (*SeqSlice[V]) Next added in v1.0.189

func (seq *SeqSlice[V]) Next() Option[V]

Next extracts the next element from the iterator and advances it.

This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements. This is similar to calling Pull() but more convenient for single-element extraction.

Returns: - Option[V]: Some(value) if an element exists, None if the iterator is exhausted.

func (SeqSlice[V]) Nth added in v1.0.181

func (seq SeqSlice[V]) Nth(n Int) Option[V]

Nth returns the nth element (0-indexed) in the sequence.

func (SeqSlice[V]) Parallel added in v1.0.151

func (seq SeqSlice[V]) Parallel(workers ...Int) SeqSlicePar[V]

Parallel runs this SeqSlice in parallel using the given number of workers.

func (SeqSlice[V]) Partition added in v1.0.63

func (seq SeqSlice[V]) Partition(fn func(v V) bool) (Slice[V], Slice[V])

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 (SeqSlice[V]) Permutations added in v1.0.63

func (seq SeqSlice[V]) Permutations() SeqSlices[V]

Slice[1, 2, 3] Slice[2, 1, 3] Slice[3, 1, 2] Slice[1, 3, 2] Slice[2, 3, 1] Slice[3, 2, 1]

The resulting iterator will contain iterators representing all possible permutations of the elements in the original iterator.

func (SeqSlice[V]) Pull added in v1.0.63

func (seq SeqSlice[V]) Pull() (func() (V, bool), func())

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 (SeqSlice[V]) Range added in v1.0.63

func (seq SeqSlice[V]) Range(fn func(v V) bool)

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(V) 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 (SeqSlice[V]) Reduce added in v1.0.178

func (seq SeqSlice[V]) Reduce(fn func(a, b V) V) Option[V]

Reduce aggregates elements of the sequence using the provided function. The first element of the sequence is used as the initial accumulator value. If the sequence is empty, it returns None[V].

Params:

  • fn (func(V, V) V): Function that combines two values into one.

Returns:

  • Option[V]: The accumulated value wrapped in Some, or None if the sequence is empty.

Example:

slice := g.Slice[int]{1, 2, 3, 4, 5}
product := slice.Iter().Reduce(func(a, b int) int { return a * b })
if product.IsSome() {
    fmt.Println(product.Some()) // 120
} else {
    fmt.Println("empty")
}

func (SeqSlice[V]) Scan added in v1.0.184

func (seq SeqSlice[V]) Scan(init V, fn func(acc, val V) V) SeqSlice[V]

Scan accumulates values of the iterator using a function, yielding all intermediate states.

The function takes an initial accumulator value and a function that combines the accumulator with each element. It yields the initial value followed by each accumulated state.

Params:

- init (V): The initial accumulator value. - fn (func(acc V, val V) V): The function that combines the accumulator with each element.

Returns:

- SeqSlice[V]: A sequence of all intermediate accumulator states.

Example usage:

numbers := g.Slice[int]{1, 2, 3, 4}.Iter()
sums := numbers.Scan(0, func(acc, val int) int {
	return acc + val
})
// sums will yield: 0, 1, 3, 6, 10

words := g.Slice[string]{"a", "b", "c"}.Iter()
concatenated := words.Scan("", func(acc, val string) string {
	return acc + val
})
// concatenated will yield: "", "a", "ab", "abc"

func (SeqSlice[V]) Skip added in v1.0.63

func (seq SeqSlice[V]) Skip(n uint) SeqSlice[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 (SeqSlice[V]) SortBy added in v1.0.63

func (seq SeqSlice[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqSlice[V]

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 V, 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) cmp.Ordering { return b.Cmp(a) }).
	Collect().
	Print()

Output: Slice[c, b, a]

The returned iterator is of type SeqSlice[V], which implements the iterator interface for further iteration over the sorted elements.

func (SeqSlice[V]) StepBy added in v1.0.63

func (seq SeqSlice[V]) StepBy(n uint) SeqSlice[V]

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 (SeqSlice[V]) Take added in v1.0.63

func (seq SeqSlice[V]) Take(n uint) SeqSlice[V]

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 (SeqSlice[V]) ToChan added in v1.0.69

func (seq SeqSlice[V]) ToChan(ctxs ...context.Context) chan V

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 (SeqSlice[V]) Unique added in v1.0.63

func (seq SeqSlice[V]) Unique() SeqSlice[V]

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 (SeqSlice[V]) Windows added in v1.0.63

func (seq SeqSlice[V]) Windows(n Int) SeqSlices[V]

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:

- n (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 (SeqSlice[V]) Zip added in v1.0.63

func (seq SeqSlice[V]) Zip(two SeqSlice[V]) SeqMapOrd[any, any]

Zip combines elements from the current sequence and another sequence into pairs, creating an ordered map with identical keys and values of type V.

type SeqSlicePar added in v1.0.151

type SeqSlicePar[V any] struct {
	// contains filtered or unexported fields
}

SeqSlicePar is a parallel iterator over a slice of elements of type T. It uses a fixed-size pool of worker goroutines to process elements concurrently.

func (SeqSlicePar[V]) All added in v1.0.151

func (p SeqSlicePar[V]) All(fn func(V) bool) bool

All returns true only if fn returns true for every element. It stops early on the first false.

func (SeqSlicePar[V]) Any added in v1.0.151

func (p SeqSlicePar[V]) Any(fn func(V) bool) bool

Any returns true if fn returns true for any element. It stops early on the first true.

func (SeqSlicePar[V]) Chain added in v1.0.151

func (p SeqSlicePar[V]) Chain(others ...SeqSlicePar[V]) SeqSlicePar[V]

Chain concatenates this SeqSlicePar with others, preserving full parallelism. Each sequence runs with its own worker pool in parallel.

func (SeqSlicePar[V]) Collect added in v1.0.151

func (p SeqSlicePar[V]) Collect() Slice[V]

Collect gathers all processed elements into a Slice.

func (SeqSlicePar[V]) Count added in v1.0.151

func (p SeqSlicePar[V]) Count() Int

Count returns the total number of elements processed.

func (SeqSlicePar[V]) Exclude added in v1.0.151

func (p SeqSlicePar[V]) Exclude(fn func(V) bool) SeqSlicePar[V]

Exclude removes elements for which fn returns true, in parallel.

func (SeqSlicePar[V]) Filter added in v1.0.151

func (p SeqSlicePar[V]) Filter(fn func(V) bool) SeqSlicePar[V]

Filter retains only elements where fn returns true.

func (SeqSlicePar[V]) FilterMap added in v1.0.184

func (p SeqSlicePar[V]) FilterMap(fn func(V) Option[V]) SeqSlicePar[V]

FilterMap applies fn to each element in parallel, keeping only Some values.

func (SeqSlicePar[V]) Find added in v1.0.151

func (p SeqSlicePar[V]) Find(fn func(V) bool) Option[V]

Find returns the first element satisfying fn, or None if no such element exists.

func (SeqSlicePar[V]) FlatMap added in v1.0.184

func (p SeqSlicePar[V]) FlatMap(fn func(V) SeqSlice[V]) SeqSlicePar[V]

FlatMap applies fn to each element in parallel, flattening the resulting sequences.

func (SeqSlicePar[V]) Flatten added in v1.0.151

func (p SeqSlicePar[V]) Flatten() SeqSlicePar[V]

Flatten unpacks nested slices or arrays in the source, returning a flat parallel sequence.

func (SeqSlicePar[V]) Fold added in v1.0.151

func (p SeqSlicePar[V]) Fold(init V, fn func(acc, v V) V) V

Fold reduces all elements into a single value, using fn to accumulate results.

func (SeqSlicePar[V]) ForEach added in v1.0.151

func (p SeqSlicePar[V]) ForEach(fn func(V))

ForEach applies fn to each element without early exit.

func (SeqSlicePar[V]) Inspect added in v1.0.151

func (p SeqSlicePar[V]) Inspect(fn func(V)) SeqSlicePar[V]

Inspect invokes fn on each element without altering the resulting sequence.

func (SeqSlicePar[V]) Map added in v1.0.151

func (p SeqSlicePar[V]) Map(fn func(V) V) SeqSlicePar[V]

Map applies fn to each element.

func (SeqSlicePar[V]) MaxBy added in v1.0.184

func (p SeqSlicePar[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]

MaxBy returns the maximum element according to the comparison function.

func (SeqSlicePar[V]) MinBy added in v1.0.184

func (p SeqSlicePar[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]

MinBy returns the minimum element according to the comparison function.

func (SeqSlicePar[V]) Partition added in v1.0.151

func (p SeqSlicePar[V]) Partition(fn func(V) bool) (Slice[V], Slice[V])

func (SeqSlicePar[V]) Range added in v1.0.151

func (p SeqSlicePar[V]) Range(fn func(V) bool)

Range applies fn to each processed element in parallel, stopping on false.

func (SeqSlicePar[V]) Reduce added in v1.0.178

func (p SeqSlicePar[V]) Reduce(fn func(a, b V) V) Option[V]

Reduce aggregates elements of the parallel sequence using the provided function. The first received element is used as the initial accumulator. If the sequence is empty, returns None[V].

func (SeqSlicePar[V]) Skip added in v1.0.151

func (p SeqSlicePar[V]) Skip(n Int) SeqSlicePar[V]

func (SeqSlicePar[V]) StepBy added in v1.0.184

func (p SeqSlicePar[V]) StepBy(n uint) SeqSlicePar[V]

StepBy yields every nth element.

func (SeqSlicePar[V]) Take added in v1.0.151

func (p SeqSlicePar[V]) Take(n Int) SeqSlicePar[V]

func (SeqSlicePar[V]) Unique added in v1.0.151

func (p SeqSlicePar[V]) Unique() SeqSlicePar[V]

Unique removes duplicate elements, preserving the first occurrence.

type SeqSlices added in v1.0.63

type SeqSlices[V any] iter.Seq[[]V]

SeqSlices is an iterator over slices of sequences of individual values.

func (SeqSlices[V]) Collect added in v1.0.63

func (seqs SeqSlices[V]) Collect() []Slice[V]

Collect gathers all elements from the iterator into a []Slice.

type Set

type Set[T comparable] map[T]struct{}

Set is a generic alias for a set implemented using a map.

func NewSet

func NewSet[T comparable](size ...Int) Set[T]

NewSet creates a new Set of the specified size or an empty Set if no size is provided.

func SetOf

func SetOf[T comparable](values ...T) Set[T]

SetOf creates a new generic set containing the provided elements.

func TransformSet added in v1.0.89

func TransformSet[T, U comparable](s Set[T], fn func(T) U) Set[U]

TransformSet applies the given function to each element of a Set and returns a new Set containing the transformed values.

Parameters:

- s: The input Set. - fn: The function to apply to each element of the input Set.

Returns:

A new Set containing the results of applying the function to each element of the input Set.

func (Set[T]) Clear

func (s Set[T]) Clear()

Clear removes all values from the Set.

func (Set[T]) Clone

func (s Set[T]) Clone() Set[T]

Clone creates a new Set that is a copy of the original Set.

func (Set[T]) Contains

func (s Set[T]) Contains(v T) bool

Contains checks if the Set contains the specified value.

func (Set[T]) ContainsAll

func (s Set[T]) ContainsAll(other Set[T]) bool

ContainsAll checks if the Set contains all elements from another Set.

func (Set[T]) ContainsAny

func (s Set[T]) ContainsAny(other Set[T]) bool

ContainsAny checks if the Set contains any element from another Set.

func (Set[T]) Difference

func (s Set[T]) Difference(other Set[T]) SeqSet[T]

Difference returns the difference between the current set and another set, i.e., elements present in the current set but not in the other set.

Parameters:

- other Set[T]: The other set to calculate the difference with.

Returns:

- Set[T]: A new Set containing the difference between the two sets.

Example usage:

s1 := g.SetOf(1, 2, 3, 4, 5)
s2 := g.SetOf(4, 5, 6, 7, 8)
diff := s1.Difference(s2)

The resulting diff will be: [1, 2, 3].

func (Set[T]) Empty

func (s Set[T]) Empty() bool

Empty checks if the Set is empty.

func (Set[T]) Eq

func (s Set[T]) Eq(other Set[T]) bool

Eq checks if two Sets are equal.

func (Set[T]) Insert added in v1.0.140

func (s Set[T]) Insert(values ...T)

Insert adds the provided elements to the set.

func (Set[T]) Intersection

func (s Set[T]) Intersection(other Set[T]) SeqSet[T]

Intersection returns the intersection of the current set and another set, i.e., elements present in both sets.

Parameters:

- other Set[T]: The other set to calculate the intersection with.

Returns:

- Set[T]: A new Set containing the intersection of the two sets.

Example usage:

s1 := g.SetOf(1, 2, 3, 4, 5)
s2 := g.SetOf(4, 5, 6, 7, 8)
intersection := s1.Intersection(s2)

The resulting intersection will be: [4, 5].

func (Set[T]) Iter

func (s Set[T]) Iter() SeqSet[T]

Iter returns an iterator (SeqSet[T]) for the Set, allowing for sequential iteration over its elements. It is commonly used in combination with higher-order functions, such as 'ForEach' or 'SetMap', to perform operations on each element of the Set.

Returns:

A SeqSet[T], which can be used for sequential iteration over the elements of the Set.

Example usage:

iter := g.SetOf(1, 2, 3).Iter()
iter.ForEach(func(val T) {
    fmt.Println(val) // Replace this with the function logic you need.
})

The 'Iter' method provides a convenient way to traverse the elements of a Set in a functional style, enabling operations like mapping or filtering. func (s Set[T]) Iter() SeqSet[T] { return seqSet(s) }

func (Set[T]) Len

func (s Set[T]) Len() Int

Len returns the number of values in the Set.

func (Set[T]) Ne

func (s Set[T]) Ne(other Set[T]) bool

Ne checks if two Sets are not equal.

func (Set[T]) NotEmpty added in v1.0.98

func (s Set[T]) NotEmpty() bool

NotEmpty checks if the Set is not empty.

func (Set[T]) Print

func (s Set[T]) Print() Set[T]

Print writes the elements of the Set to the standard output (console) and returns the Set unchanged.

func (Set[T]) Println added in v1.0.122

func (s Set[T]) Println() Set[T]

Println writes the elements of the Set to the standard output (console) with a newline and returns the Set unchanged.

func (Set[T]) Remove

func (s Set[T]) Remove(values ...T)

Remove removes the specified values from the Set.

func (Set[T]) String

func (s Set[T]) String() string

String returns a string representation of the Set.

func (Set[T]) Subset

func (s Set[T]) Subset(other Set[T]) bool

Subset checks if the current set 's' is a subset of the provided 'other' set. A set 's' is a subset of 'other' if all elements of 's' are also elements of 'other'.

Parameters:

- other Set[T]: The other set to compare with.

Returns:

- bool: true if 's' is a subset of 'other', false otherwise.

Example usage:

s1 := g.SetOf(1, 2, 3)
s2 := g.SetOf(1, 2, 3, 4, 5)
isSubset := s1.Subset(s2) // Returns true

func (Set[T]) Superset

func (s Set[T]) Superset(other Set[T]) bool

Superset checks if the current set 's' is a superset of the provided 'other' set. A set 's' is a superset of 'other' if all elements of 'other' are also elements of 's'.

Parameters:

- other Set[T]: The other set to compare with.

Returns:

- bool: true if 's' is a superset of 'other', false otherwise.

Example usage:

s1 := g.SetOf(1, 2, 3, 4, 5)
s2 := g.SetOf(1, 2, 3)
isSuperset := s1.Superset(s2) // Returns true

func (Set[T]) SymmetricDifference

func (s Set[T]) SymmetricDifference(other Set[T]) SeqSet[T]

SymmetricDifference returns the symmetric difference between the current set and another set, i.e., elements present in either the current set or the other set but not in both.

Parameters:

- other Set[T]: The other set to calculate the symmetric difference with.

Returns:

- Set[T]: A new Set containing the symmetric difference between the two sets.

Example usage:

s1 := g.SetOf(1, 2, 3, 4, 5)
s2 := g.SetOf(4, 5, 6, 7, 8)
symDiff := s1.SymmetricDifference(s2)

The resulting symDiff will be: [1, 2, 3, 6, 7, 8].

func (Set[T]) ToSlice

func (s Set[T]) ToSlice() Slice[T]

ToSlice returns a new Slice with the same elements as the Set[T].

func (Set[T]) Transform added in v1.0.89

func (s Set[T]) Transform(fn func(Set[T]) Set[T]) Set[T]

Transform applies a transformation function to the Set and returns the result.

func (Set[T]) Union

func (s Set[T]) Union(other Set[T]) SeqSet[T]

Union returns a new set containing the unique elements of the current set and the provided other set.

Parameters:

- other Set[T]: The other set to create the union with.

Returns:

- Set[T]: A new Set containing the unique elements of the current set and the provided other set.

Example usage:

s1 := g.SetOf(1, 2, 3)
s2 := g.SetOf(3, 4, 5)
union := s1.Union(s2)

The resulting union set will be: [1, 2, 3, 4, 5].

type Slice

type Slice[T any] []T

Slice is a generic alias for a slice.

func NewSlice

func NewSlice[T any](size ...Int) Slice[T]

NewSlice creates a new Slice of the given generic type T with the specified length and capacity. The size variadic parameter can have zero, one, or two integer values. If no values are provided, an empty Slice with a length and capacity of 0 is returned. If one value is provided, it sets both the length and capacity of the Slice. If two values are provided, the first value sets the length and the second value sets the capacity.

Parameters:

- size ...Int: A variadic parameter specifying the length and/or capacity of the Slice

Returns:

- Slice[T]: A new Slice of the specified generic type T with the given length and capacity

Example usage:

s1 := g.NewSlice[int]()        // Creates an empty Slice of type int
s2 := g.NewSlice[int](5)       // Creates an Slice with length and capacity of 5
s3 := g.NewSlice[int](3, 10)   // Creates an Slice with length of 3 and capacity of 10

func SliceOf

func SliceOf[T any](slice ...T) Slice[T]

SliceOf creates a new generic slice containing the provided elements.

func TransformSlice added in v1.0.89

func TransformSlice[T, U any](sl Slice[T], fn func(T) U) Slice[U]

TransformSlice applies the given function to each element of a Slice and returns a new Slice containing the transformed values.

Parameters:

- sl: The input Slice.

- fn: The function to apply to each element of the input Slice.

Returns:

A new Slice containing the results of applying the function to each element of the input Slice.

func (Slice[T]) Append

func (sl Slice[T]) Append(elems ...T) Slice[T]

Append appends the provided elements to the slice and returns the modified slice.

func (Slice[T]) AppendUnique added in v1.0.143

func (sl Slice[T]) AppendUnique(elems ...T) Slice[T]

AppendUnique appends unique elements from the provided arguments to the current slice.

The function iterates over the provided elements and checks if they are already present in the slice. If an element is not already present, it is appended to the slice. The resulting slice is returned, containing the unique elements from both the original slice and the provided elements.

Parameters:

- elems (...T): A variadic list of elements to be appended to the slice.

Returns:

- Slice[T]: A new slice containing the unique elements from both the original slice and the provided elements.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5}
slice = slice.AppendUnique(3, 4, 5, 6, 7)
fmt.Println(slice)

Output: [1 2 3 4 5 6 7].

func (Slice[T]) AsAny

func (sl Slice[T]) AsAny() Slice[any]

AsAny converts each element of the slice to the 'any' type. It returns a new slice containing the elements as 'any' g.Slice[any].

Note: AsAny is useful when you want to work with a slice of a specific type as a slice of 'any'. It can be particularly handy in conjunction with Flatten to work with nested slices of different types.

func (Slice[T]) Cap

func (sl Slice[T]) Cap() Int

Cap returns the capacity of the Slice.

func (Slice[T]) Clip

func (sl Slice[T]) Clip() Slice[T]

Clip removes unused capacity from the slice.

func (Slice[T]) Clone

func (sl Slice[T]) Clone() Slice[T]

Clone returns a copy of the slice.

func (Slice[T]) Contains

func (sl Slice[T]) Contains(val T) bool

Contains returns true if the slice contains the provided value.

func (Slice[T]) ContainsAll

func (sl Slice[T]) ContainsAll(values ...T) bool

ContainsAll checks if the Slice contains all elements from another Slice.

func (Slice[T]) ContainsAny

func (sl Slice[T]) ContainsAny(values ...T) bool

ContainsAny checks if the Slice contains any element from another Slice.

func (Slice[T]) ContainsBy added in v1.0.65

func (sl Slice[T]) ContainsBy(fn func(t T) bool) bool

ContainsBy returns true if the slice contains an element that satisfies the provided function fn, false otherwise.

func (*Slice[T]) Delete

func (sl *Slice[T]) Delete(start Int, end ...Int)

Delete removes an element or a range of elements from the Slice in-place. It modifies the original Slice by creating two slices: one from the beginning of the Slice up to the specified `start` index (exclusive), and another from the `end` index (inclusive) to the end of the Slice. These two slices are then concatenated to form the modified Slice.

Parameters:

  • start (Int): The starting index of the element or range to be removed.
  • end (Int, optional): The end index of the range to be removed. If omitted, only the element at the `start` index is removed.

Note:

The function supports negative indices. Negative values are counted from the end of the Slice: for example, -1 refers to the last element, -2 to the second-to-last, and so on.

func (Slice[T]) Empty

func (sl Slice[T]) Empty() bool

Empty returns true if the slice is empty.

func (Slice[T]) Eq

func (sl Slice[T]) Eq(other Slice[T]) bool

Eq returns true if the slice is equal to the provided other slice.

func (Slice[T]) EqBy added in v1.0.65

func (sl Slice[T]) EqBy(other Slice[T], fn func(x, y T) bool) bool

EqBy reports whether two slices are equal using an equality function on each pair of elements. If the lengths are different, EqBy returns false. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first index for which eq returns false.

func (Slice[T]) Fill

func (sl Slice[T]) Fill(val T)

Fill fills the slice with the specified value. This function is useful when you want to create an Slice with all elements having the same value. This method modifies the original slice in place.

Parameters:

- val T: The value to fill the Slice with.

Returns:

- Slice[T]: A reference to the original Slice filled with the specified value.

Example usage:

slice := g.Slice[int]{0, 0, 0}
slice.Fill(5)

The modified slice will now contain: 5, 5, 5.

func (Slice[T]) Get

func (sl Slice[T]) Get(index Int) Option[T]

Get returns the element at the given index, handling negative indices as counting from the end of the slice.

func (Slice[T]) Grow

func (sl Slice[T]) Grow(n Int) Slice[T]

Grow increases the slice's capacity, if necessary, to guarantee space for another n elements. After Grow(n), at least n elements can be appended to the slice without another allocation. If n is negative or too large to allocate the memory, Grow panics.

func (Slice[T]) Index

func (sl Slice[T]) Index(val T) Int

Index returns the index of the first occurrence of the specified value in the slice, or -1 if not found.

func (Slice[T]) IndexBy added in v1.0.65

func (sl Slice[T]) IndexBy(fn func(t T) bool) Int

IndexBy returns the index of the first element in the slice satisfying the custom comparison function provided by the user. It iterates through the slice and applies the comparison function to each element and the target value. If the comparison function returns true for any pair of elements, it returns the index of that element. If no such element is found, it returns -1.

func (*Slice[T]) Insert

func (sl *Slice[T]) Insert(i Int, values ...T)

Insert inserts values at the specified index in the slice and modifies the original slice.

Parameters:

- i Int: The index at which to insert the new values.

- values ...T: A variadic list of values to insert at the specified index.

Example usage:

slice := g.Slice[string]{"a", "b", "c", "d"}
slice.Insert(2, "e", "f")

The resulting slice will be: ["a", "b", "e", "f", "c", "d"].

func (Slice[T]) IsSortedBy added in v1.0.193

func (sl Slice[T]) IsSortedBy(fn func(a, b T) cmp.Ordering) bool

IsSortedBy checks if the slice is sorted according to the provided comparison function.

The function takes a custom comparison function as an argument and checks if the elements are sorted according to the provided logic.

Parameters:

- fn func(a, b T) cmp.Ordering: A comparison function that defines the sort order.

Returns:

- bool: true if the slice is sorted according to the comparison function, false otherwise.

Example usage:

sl := g.SliceOf(1, 2, 3, 4, 5)
sorted := sl.IsSortedBy(func(a, b int) cmp.Ordering { return cmp.Cmp(a, b) }) // returns true

func (Slice[T]) Iter

func (sl Slice[T]) Iter() SeqSlice[T]

Iter returns an iterator (SeqSlice[T]) for the Slice, allowing for sequential iteration over its elements. It is commonly used in combination with higher-order functions, such as 'ForEach', to perform operations on each element of the Slice.

Returns:

A SeqSlice[T], which can be used for sequential iteration over the elements of the Slice.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5}
iterator := slice.Iter()
iterator.ForEach(func(element int) {
	// Perform some operation on each element
	fmt.Println(element)
})

The 'Iter' method provides a convenient way to traverse the elements of a Slice in a functional style, enabling operations like mapping or filtering.

func (Slice[T]) IterReverse added in v1.0.96

func (sl Slice[T]) IterReverse() SeqSlice[T]

IterReverse returns an iterator (SeqSlice[T]) for the Slice that allows for sequential iteration over its elements in reverse order. This method is useful when you need to traverse the elements from the end to the beginning.

Returns:

A SeqSlice[T], which can be used for sequential iteration over the elements of the Slice in reverse order.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5}
iterator := slice.IterReverse()
iterator.ForEach(func(element int) {
	// Perform some operation on each element in reverse order
	fmt.Println(element)
})

The 'IterReverse' method enhances the functionality of the Slice by providing an alternative way to iterate through its elements, enhancing flexibility in how data within a Slice is accessed and manipulated.

func (Slice[T]) Join

func (sl Slice[T]) Join(sep ...T) String

Join joins the elements in the slice into a single String, separated by the provided separator (if any).

func (Slice[T]) Last

func (sl Slice[T]) Last() Option[T]

Last returns the last element of the slice.

func (Slice[T]) LastIndex

func (sl Slice[T]) LastIndex() Int

LastIndex returns the last index of the slice.

func (Slice[T]) Len

func (sl Slice[T]) Len() Int

Len returns the length of the slice.

func (Slice[T]) MaxBy added in v1.0.75

func (sl Slice[T]) MaxBy(fn func(a, b T) cmp.Ordering) T

MaxBy returns the maximum value in the slice according to the provided comparison function fn. It applies fn pairwise to the elements of the slice until it finds the maximum value. It returns the maximum value found.

Example:

s := Slice[int]{3, 1, 4, 2, 5}
maxInt := s.MaxBy(cmp.Cmp)
fmt.Println(maxInt) // Output: 5

func (Slice[T]) MinBy added in v1.0.75

func (sl Slice[T]) MinBy(fn func(a, b T) cmp.Ordering) T

MinBy returns the minimum value in the slice according to the provided comparison function fn. It applies fn pairwise to the elements of the slice until it finds the minimum value. It returns the minimum value found.

Example:

s := Slice[int]{3, 1, 4, 2, 5}
minInt := s.MinBy(cmp.Cmp)
fmt.Println(minInt) // Output: 1

func (Slice[T]) Ne

func (sl Slice[T]) Ne(other Slice[T]) bool

Ne returns true if the slice is not equal to the provided other slice.

func (Slice[T]) NeBy added in v1.0.68

func (sl Slice[T]) NeBy(other Slice[T], fn func(x, y T) bool) bool

NeBy reports whether two slices are not equal using an inequality function on each pair of elements. If the lengths are different, NeBy returns true. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first index for which fn returns true.

func (Slice[T]) NotEmpty

func (sl Slice[T]) NotEmpty() bool

NotEmpty checks if the Slice is not empty.

func (*Slice[T]) Pop

func (sl *Slice[T]) Pop() Option[T]

Pop removes and returns the last element of the slice. It mutates the original slice by removing the last element. It returns None if the slice is empty.

func (Slice[T]) Print

func (sl Slice[T]) Print() Slice[T]

Print writes the elements of the Slice to the standard output (console) and returns the Slice unchanged.

func (Slice[T]) Println added in v1.0.122

func (sl Slice[T]) Println() Slice[T]

Println writes the elements of the Slice to the standard output (console) with a newline and returns the Slice unchanged.

func (*Slice[T]) Push added in v1.0.140

func (sl *Slice[T]) Push(elems ...T)

Push appends the provided elements to the slice and modifies the original slice.

func (*Slice[T]) PushUnique added in v1.0.143

func (sl *Slice[T]) PushUnique(elems ...T)

PushUnique appends unique elements from the provided arguments to the current slice.

The function iterates over the provided elements and checks if they are already present in the slice. If an element is not already present, it is appended to the slice.

Parameters:

- elems (...T): A variadic list of elements to be appended to the slice.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5}
slice.PushUnique(3, 4, 5, 6, 7)
fmt.Println(slice)

Output: [1 2 3 4 5 6 7].

func (Slice[T]) Random

func (sl Slice[T]) Random() T

Random returns a random element from the slice.

The function uses the crypto/rand package to generate a random index within the bounds of the slice. If the slice is empty, the zero value of type T is returned.

Returns:

- T: A random element from the slice.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5}
randomElement := slice.Random()
fmt.Println(randomElement)

Output: <any random element from the slice>.

func (Slice[T]) RandomRange

func (sl Slice[T]) RandomRange(from, to Int) Slice[T]

RandomRange returns a new slice containing a random sample of elements from a subrange of the original slice. The sampling is done without replacement, meaning that each element can only appear once in the result.

func (Slice[T]) RandomSample

func (sl Slice[T]) RandomSample(sequence Int) Slice[T]

RandomSample returns a new slice containing a random sample of elements from the original slice. The sampling is done without replacement, meaning that each element can only appear once in the result.

Parameters:

- sequence int: The number of unique elements to include in the random sample.

Returns:

- Slice[T]: A new Slice containing the random sample of unique elements.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9}
sample := slice.RandomSample(3)

The resulting sample will contain 3 unique elements randomly selected from the original slice.

func (*Slice[T]) Replace

func (sl *Slice[T]) Replace(i, j Int, values ...T)

Replace replaces the elements of sl[i:j] with the given values, and modifies the original slice in place. Replace panics if sl[i:j] is not a valid slice of sl.

Parameters:

- i int: The starting index of the slice to be replaced.

- j int: The ending index of the slice to be replaced.

- values ...T: A variadic list of values to replace the existing slice.

Example usage:

slice := g.Slice[string]{"a", "b", "c", "d"}
slice.Replace(1, 3, "e", "f")

After the Replace operation, the resulting slice will be: ["a", "e", "f", "d"].

func (Slice[T]) Reverse

func (sl Slice[T]) Reverse()

Reverse reverses the order of the elements in the slice. This method modifies the original slice in place.

Returns:

- Slice[T]: The modified slice with the elements reversed.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5} slice.Reverse() fmt.Println(slice)

Output: [5 4 3 2 1].

func (Slice[T]) Set

func (sl Slice[T]) Set(index Int, val T)

Set sets the value at the specified index in the slice and returns the modified slice. This method modifies the original slice in place.

Parameters:

- index (Int): The index at which to set the new value. - val (T): The new value to be set at the specified index.

Returns:

- Slice[T]: The modified slice with the new value set at the specified index.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5} slice.Set(2, 99) fmt.Println(slice)

Output: [1 2 99 4 5].

func (Slice[T]) Shuffle

func (sl Slice[T]) Shuffle()

Shuffle shuffles the elements in the slice randomly. This method modifies the original slice in place.

The function uses the crypto/rand package to generate random indices.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5} slice.Shuffle() fmt.Println(slice)

Output: A randomly shuffled version of the original slice, e.g., [4 1 5 2 3].

func (Slice[T]) SortBy

func (sl Slice[T]) SortBy(fn func(a, b T) cmp.Ordering)

SortBy sorts the elements in the slice using the provided comparison function. It modifies the original slice in place. It requires the elements to be of a type that is comparable.

The function takes a custom comparison function as an argument and sorts the elements of the slice using the provided logic. The comparison function should return true if the element at index i should come before the element at index j, and false otherwise.

Parameters:

- f func(a, b T) cmp.Ordered: A comparison function that takes two indices i and j and returns a bool.

Example usage:

sl := NewSlice[int](1, 5, 3, 2, 4) sl.SortBy(func(a, b int) cmp.Ordering { return cmp.Cmp(a, b) }) // sorts in ascending order.

func (Slice[T]) Std

func (sl Slice[T]) Std() []T

Std returns a new slice with the same elements as the Slice[T].

func (Slice[T]) String

func (sl Slice[T]) String() string

String returns a string representation of the slice.

func (Slice[T]) SubSlice

func (sl Slice[T]) SubSlice(start, end Int, step ...Int) Slice[T]

SubSlice returns a new slice containing elements from the current slice between the specified start and end indices, with an optional step parameter to define the increment between elements. The function checks if the start and end indices are within the bounds of the original slice. If the end index is negative, it represents the position from the end of the slice. If the start index is negative, it represents the position from the end of the slice counted from the start index.

Parameters:

- start (Int): The start index of the range.

- end (Int): The end index of the range.

- step (Int, optional): The increment between elements. Defaults to 1 if not provided. If negative, the slice is traversed in reverse order.

Returns:

- Slice[T]: A new slice containing elements from the current slice between the start and end indices, with the specified step.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9}
subSlice := slice.SubSlice(1, 7, 2) // Extracts elements 2, 4, 6
fmt.Println(subSlice)

Output: [2 4 6].

func (Slice[T]) Swap

func (sl Slice[T]) Swap(i, j Int)

Swap swaps the elements at the specified indices in the slice. This method modifies the original slice in place.

Parameters:

- i (Int): The index of the first element to be swapped.

- j (Int): The index of the second element to be swapped.

Returns:

- Slice[T]: The modified slice with the elements at the specified indices swapped.

Example usage:

slice := g.Slice[int]{1, 2, 3, 4, 5} slice.Swap(1, 3) fmt.Println(slice)

Output: [1 4 3 2 5].

func (Slice[T]) ToHeap added in v1.0.181

func (sl Slice[T]) ToHeap(compareFn func(T, T) cmp.Ordering) *Heap[T]

ToHeap converts the slice to a min/max heap with the specified comparison function.

The comparison function should return:

  • cmp.Less if a < b (for min heap)
  • cmp.Greater if a > b (for max heap)
  • cmp.Equal if a == b

Example usage:

slice := g.SliceOf(5, 2, 8, 1, 9)

minHeap := slice.ToHeap(cmp.Cmp[int])	// Min heap: Pop() returns smallest
maxHeap := slice.ToHeap(func(a, b int) cmp.Ordering {
	return cmp.Cmp(b, a)
})	// Max heap: Pop() returns largest

Time complexity: O(n) Space complexity: O(n) - creates a copy of the slice

func (Slice[T]) ToStringSlice

func (sl Slice[T]) ToStringSlice() []string

ToStringSlice converts the Slice into a slice of strings.

func (Slice[T]) Transform added in v1.0.89

func (sl Slice[T]) Transform(fn func(Slice[T]) Slice[T]) Slice[T]

Transform applies a transformation function to the Slice and returns the result.

func (Slice[T]) Unpack

func (sl Slice[T]) Unpack(vars ...*T)

Unpack assigns values of the slice's elements to the variables passed as pointers. If the number of variables passed is greater than the length of the slice, the function ignores the extra variables.

Parameters:

- vars (...*T): Pointers to variables where the values of the slice's elements will be stored.

Example:

slice := g.Slice[int]{1, 2, 3, 4, 5}
var a, b, c int
slice.Unpack(&a, &b, &c)
fmt.Println(a, b, c) // Output: 1 2 3

type String

type String string

String is an alias for the string type.

func Format

func Format[T ~string](template T, args ...any) String

Format processes a template string and replaces placeholders with corresponding values from the provided arguments. It supports numeric, named, and auto-indexed placeholders, as well as dynamic invocation of methods on values.

If a placeholder cannot resolve a value or an invoked method fails, the placeholder remains unchanged in the output.

Parameters:

  • template (T ~string): A string containing placeholders enclosed in `{}`.
  • args (...any): A variadic list of arguments, which may include:
  • Positional arguments (numbers, strings, slices, structs, maps, etc.).
  • A `Named` map for named placeholders.

Placeholder Forms:

  • Numeric: `{1}`, `{2}` - References positional arguments by their 1-based index.
  • Named: `{key}`, `{key.MethodName(param1, param2)}` - References keys from a `Named` map and allows method invocation.
  • Fallback: `{key?fallback}` - Uses `fallback` if the key is not found in the named map.
  • Auto-index: `{}` - Automatically uses the next positional argument if the placeholder is empty.
  • Escaping: `\{` and `\}` - Escapes literal braces in the template string.

Returns:

  • String: A formatted string with all resolved placeholders replaced by their corresponding values.

Notes:

  • If a placeholder cannot resolve a value (e.g., missing key or out-of-range index), it remains unchanged in the output.
  • Method invocation supports any type with accessible methods. If the method or its parameters are invalid, the value remains unmodified.

Usage:

// Example 1: Numeric placeholders
result := g.Format("{1} + {2} = {3}", 1, 2, 3)

// Example 2: Named placeholders
named := g.Named{
	"name": "Alice",
	"age":  30,
}
result := g.Format("My name is {name} and I am {age} years old.", named)

// Example 3: Method invocation on values
result := g.Format("Hex: {1.Hex}, Binary: {1.Binary}", g.Int(255))

// Example 4: Fallbacks and chaining
named := g.Named{
	"name": g.String("   john  "),
	"city": g.String("New York"),
}
result := g.Format("Hello, {name.Trim.Title}. Welcome to {city?Unknown}!", named)

func NewString

func NewString[T ~string | rune | byte | ~[]rune | ~[]byte](str T) String

NewString creates a new String from the provided string.

func (String) Append added in v1.0.62

func (s String) Append(str String) String

Append appends the specified String to the current String.

func (String) Builder added in v1.0.62

func (s String) Builder() *Builder

Builder returns a new Builder initialized with the content of the String.

func (String) Bytes added in v1.0.81

func (s String) Bytes() Bytes

Bytes returns the String as an Bytes.

func (String) BytesUnsafe added in v1.0.147

func (s String) BytesUnsafe() Bytes

BytesUnsafe converts the String into Bytes without copying memory. Warning: the resulting Bytes shares the same underlying memory as the original String. If the original String is modified through unsafe operations (rare), or if it is garbage collected, the Bytes may become invalid or cause undefined behavior.

func (String) Center

func (s String) Center(length Int, pad String) String

Center justifies the String by adding padding on both sides, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.

The padding String is repeated as necessary to evenly distribute the remaining length on both sides. The padding is added to the left and right of the String.

Parameters:

  • length: The desired length of the resulting justified String.
  • pad: The String used as padding.

Example usage:

s := g.String("Hello")
result := s.Center(10, "...")
// result: "..Hello..."

func (String) Chars

func (s String) Chars() SeqSlice[String]

Chars splits the String into individual characters and returns the iterator.

func (String) Chunks

func (s String) Chunks(size Int) SeqSlice[String]

Chunks splits the String into chunks of the specified size.

This function iterates through the String, creating new String chunks of the specified size. If size is less than or equal to 0 or the String is empty, it returns an empty Slice[String]. If size is greater than or equal to the length of the String, it returns an Slice[String] containing the original String.

Parameters:

- size (Int): The size of the chunks to split the String into.

Returns:

- Slice[String]: A slice of String chunks of the specified size.

Example usage:

text := g.String("Hello, World!")
chunks := text.Chunks(4)

chunks contains {"Hell", "o, W", "orld", "!"}.

func (String) Clone added in v1.0.148

func (s String) Clone() String

Clone returns a copy of the String. It ensures that the returned String does not share underlying memory with the original String, making it safe to modify or store independently.

func (String) Cmp added in v1.0.70

func (s String) Cmp(str String) cmp.Ordering

Cmp compares two Strings and returns an cmp.Ordering indicating their relative order. The result will be cmp.Equal if s==str, cmp.Less if s < str, and cmp.Greater if s > str.

func (String) Compress added in v1.0.85

func (s String) Compress() compress

Compress returns a compress struct wrapping the given String.

func (String) Contains

func (s String) Contains(substr String) bool

Contains checks if the String contains the specified substring.

func (String) ContainsAll

func (s String) ContainsAll(substrs ...String) bool

ContainsAll checks if the given String contains all the specified substrings.

func (String) ContainsAny

func (s String) ContainsAny(substrs ...String) bool

ContainsAny checks if the String contains any of the specified substrings.

func (String) ContainsAnyChars

func (s String) ContainsAnyChars(chars String) bool

ContainsAnyChars checks if the String contains any characters from the specified String.

func (String) ContainsRune

func (s String) ContainsRune(r rune) bool

ContainsRune checks if the String contains the specified rune.

func (String) Count

func (s String) Count(substr String) Int

Count returns the number of non-overlapping instances of the substring in the String.

func (String) Cut

func (s String) Cut(start, end String, rmtags ...bool) (String, String)

Cut returns two String values. The first String contains the remainder of the original String after the cut. The second String contains the text between the first occurrences of the 'start' and 'end' strings, with tags removed if specified.

The function searches for the 'start' and 'end' strings within the String. If both are found, it returns the first String containing the remainder of the original String after the cut, followed by the second String containing the text between the first occurrences of 'start' and 'end' with tags removed if specified.

If either 'start' or 'end' is empty or not found in the String, it returns the original String as the second String, and an empty String as the first.

Parameters:

- start (String): The String marking the beginning of the text to be cut.

- end (String): The String marking the end of the text to be cut.

  • rmtags (bool, optional): An optional boolean parameter indicating whether to remove 'start' and 'end' tags from the cut text. Defaults to false.

Returns:

  • String: The first String containing the remainder of the original String after the cut, with tags removed if specified, or an empty String if 'start' or 'end' is empty or not found.

  • String: The second String containing the text between the first occurrences of 'start' and 'end', or the original String if 'start' or 'end' is empty or not found.

Example usage:

s := g.String("Hello, [world]! How are you?")
remainder, cut := s.Cut("[", "]")
// remainder: "Hello, ! How are you?"
// cut: "world"

func (String) Decode added in v1.0.85

func (s String) Decode() decode

Decode returns a decode struct wrapping the given String.

func (String) Decompress added in v1.0.85

func (s String) Decompress() decompress

Decompress returns a decompress struct wrapping the given String.

func (String) Empty

func (s String) Empty() bool

Empty checks if the String is empty.

func (String) Encode added in v1.0.85

func (s String) Encode() encode

Encode returns an encode struct wrapping the given String.

func (String) EndsWith

func (s String) EndsWith(suffix String) bool

EndsWith checks if the String ends with the specified suffix. It uses a higher-order function to perform the check.

func (String) EndsWithAny added in v1.0.90

func (s String) EndsWithAny(suffixes ...String) bool

EndsWithAny checks if the String ends with any of the provided suffixes. The method accepts a variable number of arguments, allowing for checking against multiple suffixes at once. It iterates over the provided suffixes and uses the HasSuffix function from the strings package to check if the String ends with each suffix. The function returns true if the String ends with any of the suffixes, and false otherwise.

Example usage:

s := g.String("example.com")
if s.EndsWithAny(".com", ".net") {
   // do something
}

func (String) Eq

func (s String) Eq(str String) bool

Eq checks if two Strings are equal.

func (String) EqFold

func (s String) EqFold(str String) bool

EqFold compares two String strings case-insensitively.

func (String) Fields

func (s String) Fields() SeqSlice[String]

Fields splits the String into a slice of substrings, removing any whitespace, and returns the iterator.

func (String) FieldsBy added in v1.0.76

func (s String) FieldsBy(fn func(r rune) bool) SeqSlice[String]

FieldsBy splits the String into a slice of substrings using a custom function to determine the field boundaries, and returns the iterator.

func (String) Format

func (s String) Format(template String) String

Format applies a specified format to the String object.

func (String) Gt

func (s String) Gt(str String) bool

Gt checks if the String is greater than the specified String.

func (String) Gte added in v1.0.76

func (s String) Gte(str String) bool

Gte checks if the String is greater than or equal to the specified String.

func (String) Hash

func (s String) Hash() shash

Hash returns a shash struct wrapping the given String.

func (String) Index

func (s String) Index(substr String) Int

Index returns the index of the first instance of the specified substring in the String, or -1 if substr is not present in s.

func (String) IndexRune

func (s String) IndexRune(r rune) Int

IndexRune returns the index of the first instance of the specified rune in the String.

func (String) IsASCII

func (s String) IsASCII() bool

IsASCII checks if all characters in the String are ASCII bytes.

func (String) IsDigit

func (s String) IsDigit() bool

IsDigit checks if all characters in the String are digits.

func (String) LastIndex

func (s String) LastIndex(substr String) Int

LastIndex returns the index of the last instance of the specified substring in the String, or -1 if substr is not present in s.

func (String) LeftJustify

func (s String) LeftJustify(length Int, pad String) String

LeftJustify justifies the String to the left by adding padding to the right, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.

The padding String is repeated as necessary to fill the remaining length. The padding is added to the right of the String.

Parameters:

  • length: The desired length of the resulting justified String.
  • pad: The String used as padding.

Example usage:

s := g.String("Hello")
result := s.LeftJustify(10, "...")
// result: "Hello....."

func (String) Len

func (s String) Len() Int

Len returns the length of the String.

func (String) LenRunes

func (s String) LenRunes() Int

LenRunes returns the number of runes in the String.

func (String) Lines added in v1.0.76

func (s String) Lines() SeqSlice[String]

Lines splits the String by lines and returns the iterator.

func (String) Lower

func (s String) Lower() String

Lower returns the String in lowercase.

func (String) Lt

func (s String) Lt(str String) bool

Lt checks if the String is less than the specified String.

func (String) Lte added in v1.0.76

func (s String) Lte(str String) bool

Lte checks if the String is less than or equal to the specified String.

func (String) Map

func (s String) Map(fn func(rune) rune) String

Map applies the provided function to all runes in the String and returns the resulting String.

func (String) Max

func (s String) Max(b ...String) String

Max returns the maximum of Strings.

func (String) Min

func (s String) Min(b ...String) String

Min returns the minimum of Strings.

func (String) Ne

func (s String) Ne(str String) bool

Ne checks if two Strings are not equal.

func (String) NormalizeNFC

func (s String) NormalizeNFC() String

NormalizeNFC returns a new String with its Unicode characters normalized using the NFC form.

func (String) NotEmpty

func (s String) NotEmpty() bool

NotEmpty checks if the String is not empty.

func (String) Prepend added in v1.0.62

func (s String) Prepend(str String) String

Prepend prepends the specified String to the current String.

func (String) Print

func (s String) Print() String

Print writes the content of the String to the standard output (console) and returns the String unchanged.

func (String) Println added in v1.0.122

func (s String) Println() String

Println writes the content of the String to the standard output (console) with a newline and returns the String unchanged.

func (String) Random

func (String) Random(length Int, letters ...String) String

Random generates a random String of the specified length, selecting characters from predefined sets. If additional character sets are provided, only those will be used; the default set (ASCII_LETTERS and DIGITS) is excluded unless explicitly provided.

Parameters: - count (Int): Length of the random String to generate. - letters (...String): Additional character sets to consider for generating the random String (optional).

Returns: - String: Randomly generated String with the specified length.

Example usage:

randomString := g.String.Random(10)
randomString contains a random String with 10 characters.

func (String) Reader

func (s String) Reader() *strings.Reader

Reader returns a *strings.Reader initialized with the content of String.

func (String) Regexp added in v1.0.123

func (s String) Regexp() regexps

Regexp wraps a String into an re struct to provide regex-related methods.

func (String) Remove added in v1.0.78

func (s String) Remove(matches ...String) String

Remove removes all occurrences of specified substrings from the String.

Parameters:

- matches ...String: Substrings to be removed from the string. Specify as many substrings as needed.

Returns:

- String: A new string with all specified substrings removed.

Example usage:

original := g.String("Hello, world! This is a test.")
modified := original.Remove(
    "Hello",
    "test",
)
// modified contains ", world! This is a ."

func (String) Repeat

func (s String) Repeat(count Int) String

Repeat returns a new String consisting of the specified count of the original String.

func (String) Replace

func (s String) Replace(oldS, newS String, n Int) String

Replace replaces the 'oldS' String with the 'newS' String for the specified number of occurrences.

func (String) ReplaceAll

func (s String) ReplaceAll(oldS, newS String) String

ReplaceAll replaces all occurrences of the 'oldS' String with the 'newS' String.

func (String) ReplaceMulti

func (s String) ReplaceMulti(oldnew ...String) String

ReplaceMulti creates a custom replacer to perform multiple string replacements.

Parameters:

- oldnew ...String: Pairs of strings to be replaced. Specify as many pairs as needed.

Returns:

- String: A new string with replacements applied using the custom replacer.

Example usage:

original := g.String("Hello, world! This is a test.")
replaced := original.ReplaceMulti(
    "Hello", "Greetings",
    "world", "universe",
    "test", "example",
)
// replaced contains "Greetings, universe! This is an example."

func (String) ReplaceNth

func (s String) ReplaceNth(oldS, newS String, n Int) String

ReplaceNth returns a new String instance with the nth occurrence of oldS replaced with newS. If there aren't enough occurrences of oldS, the original String is returned. If n is less than -1, the original String is also returned. If n is -1, the last occurrence of oldS is replaced with newS.

Returns:

- A new String instance with the nth occurrence of oldS replaced with newS.

Example usage:

s := g.String("The quick brown dog jumped over the lazy dog.")
result := s.ReplaceNth("dog", "fox", 2)
fmt.Println(result)

Output: "The quick brown dog jumped over the lazy fox.".

func (String) Reverse

func (s String) Reverse() String

Reverse reverses the String.

func (String) RightJustify

func (s String) RightJustify(length Int, pad String) String

RightJustify justifies the String to the right by adding padding to the left, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.

The padding String is repeated as necessary to fill the remaining length. The padding is added to the left of the String.

Parameters:

  • length: The desired length of the resulting justified String.
  • pad: The String used as padding.

Example usage:

s := g.String("Hello")
result := s.RightJustify(10, "...")
// result: ".....Hello"

func (String) Runes added in v1.0.81

func (s String) Runes() Slice[rune]

Runes returns the String as a slice of runes.

func (String) Similarity

func (s String) Similarity(str String) Float

Similarity calculates the similarity between two Strings using the Levenshtein distance algorithm and returns the similarity percentage as an Float.

The function compares two Strings using the Levenshtein distance, which measures the difference between two sequences by counting the number of single-character edits required to change one sequence into the other. The similarity is then calculated by normalizing the distance by the maximum length of the two input Strings.

Parameters:

- str (String): The String to compare with s.

Returns:

- Float: The similarity percentage between the two Strings as a value between 0 and 100.

Example usage:

s1 := g.String("kitten")
s2 := g.String("sitting")
similarity := s1.Similarity(s2) // 57.14285714285714

func (String) Split

func (s String) Split(sep ...String) SeqSlice[String]

Split splits the String by the specified separator and returns the iterator.

func (String) SplitAfter added in v1.0.76

func (s String) SplitAfter(sep String) SeqSlice[String]

SplitAfter splits the String after each instance of the specified separator and returns the iterator.

func (String) SplitN

func (s String) SplitN(sep String, n Int) Slice[String]

SplitN splits the String into substrings using the provided separator and returns an Slice[String] of the results. The n parameter controls the number of substrings to return: - If n is negative, there is no limit on the number of substrings returned. - If n is zero, an empty Slice[String] is returned. - If n is positive, at most n substrings are returned.

func (String) StartsWith

func (s String) StartsWith(prefix String) bool

StartsWith checks if the String starts with the specified prefix. It uses a higher-order function to perform the check.

func (String) StartsWithAny added in v1.0.90

func (s String) StartsWithAny(prefixes ...String) bool

StartsWithAny checks if the String starts with any of the provided prefixes. The method accepts a variable number of arguments, allowing for checking against multiple prefixes at once. It iterates over the provided prefixes and uses the HasPrefix function from the strings package to check if the String starts with each prefix. The function returns true if the String starts with any of the prefixes, and false otherwise.

Example usage:

s := g.String("http://example.com")
if s.StartsWithAny("http://", "https://") {
   // do something
}

func (String) Std

func (s String) Std() string

Std returns the String as a string.

func (String) StripPrefix added in v1.0.81

func (s String) StripPrefix(prefix String) String

StripPrefix trims the specified prefix from the String.

func (String) StripSuffix added in v1.0.81

func (s String) StripSuffix(suffix String) String

StripSuffix trims the specified suffix from the String.

func (String) SubString added in v1.0.127

func (s String) SubString(start, end Int, step ...Int) String

SubString extracts a substring from the String starting at the 'start' index and ending before the 'end' index. The function also supports an optional 'step' parameter to define the increment between indices in the substring. If 'start' or 'end' index is negative, they represent positions relative to the end of the String: - A negative 'start' index indicates the position from the end of the String, moving backward. - A negative 'end' index indicates the position from the end of the String. The function ensures that indices are adjusted to fall within the valid range of the String's length. If indices are out of bounds or if 'start' exceeds 'end', the function returns the original String unmodified.

func (String) Title

func (s String) Title() String

Title converts the String to title case.

func (String) ToBigInt added in v1.0.84

func (s String) ToBigInt() Option[*big.Int]

ToBigInt attempts to convert the String receiver into an Option containing a *big.Int. This function assumes the string represents a numerical value, which can be in decimal, hexadecimal (prefixed with "0x"), or octal (prefixed with "0") format. The function leverages the SetString method of the math/big package, automatically detecting the numeric base when set to 0.

If the string is correctly formatted and represents a valid number, ToBigInt returns a Some containing the *big.Int parsed from the string. If the string is empty, contains invalid characters, or does not conform to a recognizable numeric format, ToBigInt returns a None, indicating that the conversion was unsuccessful.

Returns:

  • An Option[*big.Int] encapsulating the conversion result. It returns Some[*big.Int] with the parsed value if successful, otherwise None[*big.Int] if the parsing fails.

func (String) ToFloat

func (s String) ToFloat() Result[Float]

ToFloat tries to parse the String as a float64 and returns an Float.

func (String) ToInt

func (s String) ToInt() Result[Int]

ToInt tries to parse the String as an int and returns an Int.

func (String) Transform added in v1.0.89

func (s String) Transform(fn func(String) String) String

Transform applies a transformation function to the String and returns the result.

func (String) Trim

func (s String) Trim() String

Trim removes leading and trailing white space from the String.

func (String) TrimEnd added in v1.0.81

func (s String) TrimEnd() String

TrimEnd removes trailing white space from the String.

func (String) TrimEndSet added in v1.0.82

func (s String) TrimEndSet(cutset String) String

TrimEndSet removes the specified set of characters from the end of the String.

func (String) TrimSet added in v1.0.82

func (s String) TrimSet(cutset String) String

TrimSet removes the specified set of characters from both the beginning and end of the String.

func (String) TrimStart added in v1.0.81

func (s String) TrimStart() String

TrimStart removes leading white space from the String.

func (String) TrimStartSet added in v1.0.82

func (s String) TrimStartSet(cutset String) String

TrimStartSet removes the specified set of characters from the beginning of the String.

func (String) Truncate added in v1.0.126

func (s String) Truncate(max Int) String

Truncate shortens the String to the specified maximum length. If the String exceeds the specified length, it is truncated, and an ellipsis ("...") is appended to indicate the truncation.

If the length of the String is less than or equal to the specified maximum length, the original String is returned unchanged.

The method respects Unicode characters and truncates based on the number of runes, not bytes.

Parameters:

  • max: The maximum number of runes allowed in the resulting String.

Returns:

  • A new String truncated to the specified maximum length with "..." appended if truncation occurs. Otherwise, returns the original String.

Example usage:

s := g.String("Hello, World!")
result := s.Truncate(5)
// result: "Hello..."

s2 := g.String("Short")
result2 := s2.Truncate(10)
// result2: "Short"

s3 := g.String("😊😊😊😊😊")
result3 := s3.Truncate(3)
// result3: "😊😊😊..."

func (String) Upper

func (s String) Upper() String

Upper returns the String in uppercase.

type Unit added in v1.0.174

type Unit struct{}

Unit represents an empty value. Used in contexts where a function needs to return "something" but the actual value doesn't matter, only success/failure status.

Directories

Path Synopsis
cell command
cmp command
dirs command
files command
iter command
monads command
pool command
slices command
f
internal
filelock
Package filelock provides a platform-independent API for advisory file locking.
Package filelock provides a platform-independent API for advisory file locking.
filelock/syscall/windows/sysdll
Package sysdll is an internal leaf package that records and reports which Windows DLL names are used by Go itself.
Package sysdll is an internal leaf package that records and reports which Windows DLL names are used by Go itself.
Package ref provides a utility function for creating a pointer to a value.
Package ref provides a utility function for creating a pointer to a value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL