Skip to content

Latest commit

 

History

History
128 lines (85 loc) · 2.69 KB

File metadata and controls

128 lines (85 loc) · 2.69 KB

🧩 Helper Functions

The root collection package includes a set of general-purpose helper functions. These standalone utilities complement the collection types and simplify common Go patterns.


🛠 Available Helpers

Function Purpose
Value Returns the given value unchanged (no-op).
ValueFunc Calls a callback and returns its result (lazy evaluation).
Head Safely returns the first element of a slice.
Last Safely returns the last element of a slice.
WhenValue Inline conditional for values.
WhenFunc Inline conditional for callbacks (lazy).
Error Types Specialized errors for collection operations.
Shared Types Common type constraints and structures.

💎 Value

func Value[T any](value T) T

Returns the given value unchanged. Useful as a no-op callback or for consistent value resolution patterns.

v := collection.Value(42) // 42

💎 ValueFunc

func ValueFunc[T any](callback func() T) T

Calls the given callback and returns its result. Useful for deferred evaluation.

v := collection.ValueFunc(func() string {
    return computeExpensiveDefault()
})

💎 Head

func Head[T any](items []T) (T, bool)

Returns the first element of a slice. Returns false if the slice is empty.

first, ok := collection.Head([]string{"alice", "bob"})
// first = "alice", ok = true

💎 Last

func Last[T any](items []T) (T, bool)

Returns the last element of a slice. Returns false if the slice is empty.


💎 WhenValue

func WhenValue[T any](condition bool, value T, defaults ...T) T

Returns value if condition is true, otherwise returns the first default or the zero value.

label := collection.WhenValue(isAdmin, "Admin Panel", "Dashboard")

💎 WhenFunc

func WhenFunc[T any](condition bool, callback func() T, defaults ...func() T) T

Like WhenValue but accepts callbacks for deferred evaluation. Only the required branch is executed.


🛡 Error Types

ItemNotFoundError

Returned when a requested item is missing (e.g., FirstOrFail, Sole).

MultipleItemsFoundError

Returned by Sole when more than one item matches the predicate.


🧩 Shared Types

Numeric

A type constraint for numeric types, used by aggregation functions like Sum and Avg.

Pair[K, V]

A generic key-value pair used by Combine and MapCollection.

type Pair[K any, V any] struct {
    Key   K
    Value V
}

👉 Back to Overview