coll

package module
v0.0.0-...-65944f3 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2025 License: MIT Imports: 5 Imported by: 0

README

= Comfy Gopher - Collections

image:https://codecov.io/gh/comfygopher/collections/graph/badge.svg?token=I5QQ2SU3E7[codecov,link=https://codecov.io/gh/comfygopher/collections]
image:https://img.shields.io/coderabbit/prs/github/comfygopher/collections?utm_source=oss&utm_medium=github&utm_campaign=comfygopher%2Fcollections&labelColor=5b5b5b&color=FF570A&link=https%3A%2F%2Fcoderabbit.ai&label=CodeRabbit+Reviews[CodeRabbit Pull Request Reviews]
image:https://goreportcard.com/badge/github.com/comfygopher/collections[Go Report Card,link=https://goreportcard.com/report/github.com/comfygopher/collections]

== What is Comfy Gopher?

*Comfy Gopher is a Set of general-purpose Tools, Utilities, and Data Structures for Comfortable Development*

These tools prioritize speed and ease of development over strict efficiency or full compliance with Go philosophy.
They accelerate development and enhance the experience, by reducing the cognitive load,
making them well suited for rapid prototyping.

== Comfy Gopher - Collections package

=== Goals

1. Provide convenient abstraction for collection data structures
1. Focus on developer experience
1. Reduce repetition of common collections operations
1. Address the missing ordered map data structure
1. Provide API for in-place modifications of collections
1. Reduce strain of juggling between empty slice pointers `[]V(nil) vs []V{}`

=== No-goals

This is a set of elements that the Collections package are NOT trying to achieve:

1. Thread-safety
+
You must implement your own thread-safety.

1. Superb efficiency
+
Although care is taken to ensure that the data structures used are efficient, exceptional efficiency is not the main goal here.

== Alternatives

There is a very nice library https://github.com/charbz/gophers[github.com/charbz/gophers].
Its API is a mix of mutable and immutable operations, which can be confusing.
Most of the methods there do return a new collection instance though. This has its applications,
but at the same time it presents some inconveniences when working with extensive amount of
other libraries that expect mutable elements.

Documentation

Overview

Package coll provides a set of collection data structures.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrOutOfBounds is returned when an operation is performed on an index that is out of bounds.
	ErrOutOfBounds = errors.New("index out of bounds")

	// ErrEmptyCollection is returned when an operation is performed on an empty collection.
	ErrEmptyCollection = fmt.Errorf("%w: collection is empty", ErrOutOfBounds)

	// ErrValueNotFound is returned when a value is not found in a collection.
	ErrValueNotFound = errors.New("value not found")
)

Functions

func Copy

func Copy[C Base[V], V any](coll C) C

Copy creates a copy of the given collection.

Types

type Base

type Base[V any] interface {
	// IsEmpty returns true if the collection is empty.
	IsEmpty() bool

	// Len returns the number of elements in the collection.
	Len() int

	// Values returns an iterator over all elements in the collection.
	// This method is implicitly ordered on all collections that also implement the Ordered interface.
	// There is no guarantee that the order of elements will be preserved if the collection does not implement
	// the Ordered interface.
	Values() iter.Seq[V]
}

Base is the base interface for all collections.

type BasePairs

type BasePairs[K comparable, V any] interface {
	Base[Pair[K, V]]
}

BasePairs is the base interface for all collections of key-value pairs.

type Cmp

type Cmp[V cmp.Ordered] interface {
	// ContainsValue returns true if the collection contains the given value.
	// Implementations of this method should utilize ValuesCounter making this operation O(1)
	// Alias: HasValue
	ContainsValue(v V) bool

	// CountValues returns the number of times the given value appears in the collection.
	// Implementations of this method should utilize ValuesCounter making this operation O(1)
	CountValues(v V) int

	// HasValue is an alias for ContainsValue.
	// Deprecated: use ContainsValue instead.
	HasValue(v V) bool

	// IndexOf returns the index of the first occurrence of the given value.
	IndexOf(val V) (i int, found bool)

	// LastIndexOf returns the index of the last occurrence of the given value.
	LastIndexOf(val V) (i int, found bool)
}

Cmp is a collection of elements of type cmp.Ordered It is called `cmp` (from `comparable`) instead of `ordered` to avoid confusion with collections that are not preserving order of elements (like the Go's native map).

type CmpMap

type CmpMap[K comparable, V cmp.Ordered] interface {
	Map[K, V]
	CmpMutable[V]
}

CmpMap is a map of key-value pairs where values implement the cmp.Ordered interface

func NewCmpMap

func NewCmpMap[K comparable, V cmp.Ordered]() CmpMap[K, V]

NewCmpMap creates a new CmpMap instance.

func NewCmpMapFrom

func NewCmpMapFrom[K comparable, V cmp.Ordered](s []Pair[K, V]) CmpMap[K, V]

NewCmpMapFrom creates a new CmpMap instance from a slice of pairs.

type CmpMutable

type CmpMutable[V cmp.Ordered] interface {
	Cmp[V]

	// RemoveValues removes all occurrences of the given value.
	// Returns the number of removed items.
	RemoveValues(v ...V) (count int)

	// SortAsc sorts the collection in ascending order.
	SortAsc()

	// SortDesc sorts the collection in descending order.
	SortDesc()
}

CmpMutable is a mutable collection of elements of type cmp.Ordered It is called `cmp` (from `comparable`) instead of `ordered` to avoid confusion with collections that are not preserving order of elements (like the Go's native map).

type CmpOrdered

type CmpOrdered[V cmp.Ordered] interface {
	OrderedMutable[V]
	CmpMutable[V]
}

CmpOrdered is a list of elements of type cmp.Ordered

type CmpSequence

type CmpSequence[V cmp.Ordered] interface {
	Sequence[V]
	CmpMutable[V]
}

CmpSequence is a ordered collection of elements that can be compared.

func NewCmpSequence

func NewCmpSequence[V cmp.Ordered]() CmpSequence[V]

NewCmpSequence creates a new CmpSequence instance.

func NewCmpSequenceFrom

func NewCmpSequenceFrom[V cmp.Ordered](s []V) CmpSequence[V]

NewCmpSequenceFrom creates a new CmpSequence instance from a slice.

type Comparator

type Comparator[V any] = func(a, b V) int

Comparator is a comparator function.

type Indexed

type Indexed[V any] interface {
	Ordered[V]

	// At returns the element at the given index.
	At(idx int) (V, bool)

	// AtOrDefault returns the element at the given index or the default value if the index is out of bounds.
	AtOrDefault(idx int, defaultValue V) V
}

Indexed interface indicates that given collection can be accessed by index.

type IndexedMapper

type IndexedMapper[V any] = func(i int, val V) V

IndexedMapper is used to map an element of a collection to a new value.

type IndexedMutable

type IndexedMutable[V any] interface {
	Indexed[V]
	Mutable[V]

	// RemoveAt removes the element at the given index.
	RemoveAt(idx int) (removed V, err error)

	// Sort sorts the collection using the given comparator.
	Sort(cmp Comparator[V])
}

IndexedMutable is a mutable collection that can be modified based on the indexes.

type IndexedPredicate

type IndexedPredicate[V any] = func(i int, val V) (valid bool)

IndexedPredicate is used to verify that collection element meets certain conditions.

type IndexedVisitor

type IndexedVisitor[V any] = func(i int, val V)

IndexedVisitor is used to visit each element of a collection.

type List

type List[V any] interface {
	OrderedMutable[V]

	// InsertAt inserts the given value at the given index.
	InsertAt(i int, val V) error
}

List is a mutable collection of elements.

type Map

type Map[K comparable, V any] interface {
	BasePairs[K, V]
	IndexedMutable[Pair[K, V]]
	OrderedMutable[Pair[K, V]]

	// Get returns the value associated with the given key.
	Get(key K) (val V, ok bool)

	// GetOrDefault returns the value associated with the given key or the default value if the key is not found.
	GetOrDefault(k K, defaultValue V) V

	// Has returns true if the given key is present in the map.
	Has(key K) bool

	// Keys returns an iterator over all keys in the map.
	Keys() iter.Seq[K]

	// KeyValues returns an iterator over all key-value pairs in the map.
	KeyValues() iter.Seq2[K, V]

	// Remove removes the value associated with the given key.
	Remove(key K) // TODO: Replace with Remove(key ...V)

	// RemoveMany removes the values associated with the given keys.
	RemoveMany(keys []K) // TODO: remove after implementing the above Remove functionality

	// Set sets the value associated with the given key.
	Set(key K, val V)

	// SetMany sets the Pair items associated with the given keys.
	SetMany(s []Pair[K, V])

	// Sort sorts the map using the given comparator.
	Sort(compare PairComparator[K, V])

	// Values returns values iterator.
	// Use KeyValues for key-value iterator.
	Values() iter.Seq[Pair[K, V]]
}

Map is a collection of key-value pairs.

func NewMap

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

NewMap creates a new Map instance. Note that there is no NewMapFrom constructor, because it would create collection in random order.

func NewMapFrom

func NewMapFrom[K comparable, V any](s []Pair[K, V]) Map[K, V]

NewMapFrom creates a new Map instance from a slice of pairs.

type Mapper

type Mapper[V any] = func(val V) V

Mapper is used to map an element of a collection to a new value.

type Mutable

type Mutable[V any] interface {
	Base[V]

	// Apply applies the given function to each element of the collection.
	Apply(f Mapper[V])

	// Clear removes all elements from the collection.
	Clear()

	// RemoveMatching removes all elements that match the given predicate.
	// Returns the number of removed items.
	RemoveMatching(predicate Predicate[V]) (count int)
}

Mutable is a collection with methods that modify its contents.

type Ordered

type Ordered[V any] interface {
	Base[V]

	// ValuesRev returns an iterator over all elements in the collection in reverse order.
	ValuesRev() iter.Seq[V]
}

Ordered interface indicates that given collection preserves the order of elements.

type OrderedMutable

type OrderedMutable[V any] interface {
	Ordered[V]
	Mutable[V]

	// Append appends the given values to the collection.
	Append(v ...V)

	// AppendColl appends values of the given collection to the current collection.
	AppendColl(c Ordered[V])

	// Prepend prepends the given values to the collection.
	Prepend(v ...V)

	// Reverse reverses the order of elements in the collection.
	Reverse()
}

OrderedMutable is a mutable collection that can be modified by appending, prepending and inserting elements.

type Pair

type Pair[K comparable, V any] interface {
	// Key returns the key of the pair.
	Key() K

	// Val returns the value of the pair.
	Val() V

	// SetVal sets the value of the pair.
	SetVal(v V)
	// contains filtered or unexported methods
}

Pair holds a key-value set of elements. It is used as the underlying value type for Map and similar collections. It is sealed with unexported `copy` method to prevent implementations outside the package that may allow changing the key. Tampering with the keys would most likely result in breaking the internal consistency of the collection.

func NewPair

func NewPair[K comparable, V any](key K, val V) Pair[K, V]

NewPair creates a new Pair instance.

type PairComparator

type PairComparator[K comparable, V any] = Comparator[Pair[K, V]]

PairComparator is a comparator function for key-value pairs.

type Predicate

type Predicate[V any] = func(val V) (valid bool)

Predicate is used to verify that collection element meets certain conditions.

type Sequence

type Sequence[V any] interface {
	OrderedMutable[V]
}

Sequence is a list-like collection that wraps an underlying Go slice.

Compared to a List, a Sequence allows for efficient O(1) access to arbitrary elements but slower insertion and removal time, making it suitable for situations where fast random access is needed.

func NewSequence

func NewSequence[V any]() Sequence[V]

NewSequence creates a new Sequence instance.

func NewSequenceFrom

func NewSequenceFrom[V any](l []V) Sequence[V]

NewSequenceFrom creates a new Sequence instance from a slice.

type Set

type Set[K comparable, V cmp.Ordered] interface {
	CmpMap[K, V]
}

Set is a collection of unique elements.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL