col

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2025 License: MIT Imports: 4 Imported by: 0

README

col - Collection Utility Functions for Go

The col package provides a comprehensive set of utility functions for working with collections (slices and maps) in Go. It's inspired by libraries like Lodash for JavaScript and offers a wide range of functions to make working with collections easier and more expressive.

Installation

go get github.com/gflydev/utils/col

Usage

import "github.com/gflydev/utils/col"

Functions

Collection Operations
CountBy

Counts elements in a collection based on a key generated by an iteratee function.

result := col.CountBy([]int{1, 2, 3, 4}, func(n int) string {
    if n%2 == 0 {
        return "even"
    }
    return "odd"
})
// result: map[string]int{"odd": 2, "even": 2}

result := col.CountBy([]int{1, 3, 5}, func(n int) string {
    if n%2 == 0 {
        return "even"
    }
    return "odd"
})
// result: map[string]int{"odd": 3}
Every

Checks if all elements in a collection satisfy a predicate.

result := col.Every([]int{2, 4, 6}, func(n int) bool { 
    return n%2 == 0 
})
// result: true

result := col.Every([]int{2, 3, 6}, func(n int) bool { 
    return n%2 == 0 
})
// result: false
Filter

Filters elements in a collection based on a predicate.

result := col.Filter([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: []int{2, 4}

result := col.Filter([]int{1, 3, 5}, func(n int) bool { 
    return n%2 == 0 
})
// result: []int{}
Find

Returns the first element in a collection that satisfies a predicate.

result, ok := col.Find([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: 2, ok: true

result, ok := col.Find([]int{1, 3, 5}, func(n int) bool { 
    return n%2 == 0 
})
// result: 0, ok: false
FindLast

Returns the last element in a collection that satisfies a predicate.

result, ok := col.FindLast([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: 4, ok: true

result, ok := col.FindLast([]int{1, 3, 5}, func(n int) bool { 
    return n%2 == 0 
})
// result: 0, ok: false
Includes

Checks if a collection includes a specific value.

result := col.Includes([]int{1, 2, 3, 4}, 3)
// result: true

result := col.Includes([]int{1, 2, 3, 4}, 5)
// result: false
Size

Returns the size of a collection.

Parameters:

  • collection: The slice to measure

Returns:

  • int: The number of elements in the collection
result := col.Size([]int{1, 2, 3, 4})
// result: 4

result := col.Size([]int{})
// result: 0
Some

Checks if at least one element in a collection satisfies a predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for elements to check

Returns:

  • bool: True if any element satisfies the predicate, false otherwise
result := col.Some([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: true

result := col.Some([]int{1, 3, 5}, func(n int) bool { 
    return n%2 == 0 
})
// result: false
SortBy

Sorts a collection based on a key generated by an iteratee function.

Parameters:

  • collection: The slice to process
  • iteratee: The function that returns the value to sort by

Returns:

  • []T: A new sorted slice
result := col.SortBy([]int{4, 2, 1, 3}, func(n int) int { 
    return n 
})
// result: []int{1, 2, 3, 4}

type User struct {
    Name string
    Age  int
}

users := []User{
    {Name: "Alice", Age: 30},
    {Name: "Bob", Age: 25},
    {Name: "Charlie", Age: 35},
}

result := col.SortBy(users, func(u User) int { 
    return u.Age 
})
// result: []User{
//    {Name: "Bob", Age: 25},
//    {Name: "Alice", Age: 30},
//    {Name: "Charlie", Age: 35},
// }
Map

Transforms each element in a collection using an iteratee function.

Parameters:

  • collection: The slice to process
  • iteratee: The function to transform each element

Returns:

  • []R: A new slice containing the transformed elements
result := col.Map([]int{1, 2, 3, 4}, func(n int) int { 
    return n * 2 
})
// result: []int{2, 4, 6, 8}
Reject

Returns elements in a collection that don't satisfy a predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for elements to exclude

Returns:

  • []T: A new slice containing only the elements that don't satisfy the predicate
result := col.Reject([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: []int{1, 3}
Reduce

Reduces a collection to a single value by iteratively applying an iteratee function.

Parameters:

  • collection: The slice to process
  • iteratee: The function to apply to each element with the accumulator
  • accumulator: The initial value of the accumulator

Returns:

  • R: The final accumulated value
result := col.Reduce([]int{1, 2, 3, 4}, func(acc int, n int) int { 
    return acc + n 
}, 0)
// result: 10
GroupBy

Groups elements in a collection based on a key generated by an iteratee function.

result := col.GroupBy([]int{1, 2, 3, 4}, func(n int) string {
    if n%2 == 0 {
        return "even"
    }
    return "odd"
})
// result: map[string][]int{"odd": {1, 3}, "even": {2, 4}}
KeyBy

Creates an object composed of keys generated from the results of running each element of collection through iteratee.

Parameters:

  • collection: The slice to process
  • iteratee: The function to generate the key for each element

Returns:

  • map[K]T: A map where keys are generated by the iteratee function and values are the original elements
type User struct {
    ID   int
    Name string
}

users := []User{
    {ID: 1, Name: "Alice"},
    {ID: 2, Name: "Bob"},
}

result := col.KeyBy(users, func(u User) int { 
    return u.ID 
})
// result: map[int]User{
//    1: {ID: 1, Name: "Alice"},
//    2: {ID: 2, Name: "Bob"},
// }
Partition

Splits a collection into two groups: one with elements that satisfy a predicate and one with elements that don't.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for elements to include in the first group

Returns:

  • [][]T: A slice containing two slices: the first with elements that satisfy the predicate, the second with elements that don't satisfy the predicate
result := col.Partition([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: [][]int{{2, 4}, {1, 3}}
ReduceRight

Reduces a collection to a value by iterating through the collection from right to left.

Parameters:

  • collection: The slice to process
  • iteratee: The function to apply to each element with the accumulator
  • accumulator: The initial value of the accumulator

Returns:

  • R: The final accumulated value
result := col.ReduceRight([]int{1, 2, 3, 4}, func(acc int, n int) int { 
    return acc - n 
}, 0)
// result: -10
OrderBy

Sorts a collection based on a key generated by an iteratee function, with control over ascending or descending order.

result := col.OrderBy([]int{4, 2, 1, 3}, func(n int) int { 
    return n 
}, true)
// result: []int{1, 2, 3, 4}

result := col.OrderBy([]int{4, 2, 1, 3}, func(n int) int { 
    return n 
}, false)
// result: []int{4, 3, 2, 1}
Iteration Functions
ForEach

Iterates over elements in a collection and applies an iteratee function.

sum := 0
col.ForEach([]int{1, 2, 3, 4}, func(n int) {
    sum += n
})
// sum: 10
MapWithIndex

Like Map, but the iteratee function also receives the index of the element.

Parameters:

  • collection: The slice to process
  • iteratee: The function to transform each element with its index

Returns:

  • []R: A new slice containing the transformed elements
result := col.MapWithIndex([]int{1, 2, 3, 4}, func(n int, i int) int { 
    return n * i 
})
// result: []int{0, 2, 6, 12}
ForEachWithIndex

Like ForEach, but the iteratee function also receives the index of the element.

sum := 0
col.ForEachWithIndex([]int{1, 2, 3, 4}, func(n int, i int) {
    sum += n * i
})
// sum: 20
Random Functions
Sample

Returns a random element from a collection.

Parameters:

  • collection: The slice to process

Returns:

  • T: A random element from the collection
  • bool: True if an element was returned, false if the collection was empty
result, ok := col.Sample([]int{1, 2, 3, 4})
// result: a random element from the collection, ok: true

result, ok := col.Sample([]int{})
// result: 0, ok: false
SampleSize

Returns n random elements from a collection.

Parameters:

  • collection: The slice to process
  • n: The number of random elements to return

Returns:

  • []T: A slice containing n random elements from the collection
result := col.SampleSize([]int{1, 2, 3, 4}, 2)
// result: 2 random elements from the collection

result := col.SampleSize([]int{1, 2, 3, 4}, 6)
// result: a shuffled version of the original collection
Map Operations
ForEachMap

Iterates over elements in a map and applies an iteratee function.

m := map[string]int{"a": 1, "b": 2, "c": 3}
sum := 0
col.ForEachMap(m, func(v int, k string) {
    sum += v
})
// sum: 6
MapMap

Transforms each element in a map using an iteratee function.

m := map[string]int{"a": 1, "b": 2, "c": 3}
result := col.MapMap(m, func(v int, k string) string { 
    return k + string(rune('0' + v)) 
})
// result: []string{"a1", "b2", "c3"} (order may vary)
FilterMap

Filters elements in a map based on a predicate.

m := map[string]int{"a": 1, "b": 2, "c": 3}
result := col.FilterMap(m, func(v int, k string) bool { 
    return v%2 == 1 
})
// result: map[string]int{"a": 1, "c": 3}
ReduceMap

Reduces a map to a single value by iteratively applying an iteratee function.

m := map[string]int{"a": 1, "b": 2, "c": 3}
result := col.ReduceMap(m, func(acc string, v int, k string) string { 
    return acc + k 
}, "")
// result: "abc" (order may vary)
Statistical Functions
Avg

Calculates the average of values in a collection.

result := col.Avg([]int{1, 2, 3, 4}, func(n int) float64 { 
    return float64(n) 
})
// result: 2.5
Array Manipulation
Chunk

Splits an array into chunks of the specified size.

result := col.Chunk([]int{1, 2, 3, 4, 5}, 2)
// result: [][]int{{1, 2}, {3, 4}, {5}}
Contains

Checks if a collection contains a specific element.

result := col.Contains([]int{1, 2, 3, 4}, 3)
// result: true

result := col.Contains([]int{1, 2, 3, 4}, 5)
// result: false
ContainsFn

Checks if a collection contains an element that satisfies the given predicate.

result := col.ContainsFn([]int{1, 2, 3, 4}, func(n int) bool { 
    return n > 2 
})
// result: true

result := col.ContainsFn([]int{1, 2, 3, 4}, func(n int) bool { 
    return n > 5 
})
// result: false
Count

Returns the number of elements in a collection.

Parameters:

  • collection: The slice to count

Returns:

  • int: The number of elements in the collection
result := col.Count([]int{1, 2, 3, 4})
// result: 4

result := col.Count([]int{})
// result: 0
Reverse

Reverses the order of the collection's items.

Parameters:

  • collection: The slice to reverse

Returns:

  • []T: A new slice with the elements in reverse order
result := col.Reverse([]int{1, 2, 3, 4})
// result: []int{4, 3, 2, 1}
Slice

Returns a slice of the collection starting at the given index.

Parameters:

  • collection: The slice to extract a portion from
  • start: The starting index (can be negative to count from the end)

Returns:

  • []T: A new slice containing elements from the start index to the end of the collection
result := col.Slice([]int{1, 2, 3, 4}, 1)
// result: []int{2, 3, 4}

result := col.Slice([]int{1, 2, 3, 4}, -2)
// result: []int{3, 4}

result := col.Slice([]int{1, 2, 3, 4}, 5)
// result: []int{}
SliceWithLength

Returns a slice of the collection starting at the given index with the specified length.

Parameters:

  • collection: The slice to extract a portion from
  • start: The starting index (can be negative to count from the end)
  • length: The number of elements to include in the result

Returns:

  • []T: A new slice containing the specified number of elements from the start index
result := col.SliceWithLength([]int{1, 2, 3, 4}, 1, 2)
// result: []int{2, 3}

result := col.SliceWithLength([]int{1, 2, 3, 4}, -2, 2)
// result: []int{3, 4}

result := col.SliceWithLength([]int{1, 2, 3, 4}, 0, 10)
// result: []int{1, 2, 3, 4}
Shuffle

Randomly shuffles the items in the collection.

Parameters:

  • collection: The slice to shuffle

Returns:

  • []T: A new slice with the elements in random order
result := col.Shuffle([]int{1, 2, 3, 4})
// result: []int{2, 3, 1, 4} (random order)

result := col.Shuffle([]int{})
// result: []int{}
Collapse

Flattens a collection of collections into a single collection.

result := col.Collapse([][]int{{1, 2}, {3, 4}})
// result: []int{1, 2, 3, 4}
CrossJoin

Creates a cartesian product of multiple collections.

result := col.CrossJoin([]int{1, 2}, []int{3, 4}, []int{5, 6})
// result: [][]int{{1, 3, 5}, {1, 3, 6}, {1, 4, 5}, {1, 4, 6}, {2, 3, 5}, {2, 3, 6}, {2, 4, 5}, {2, 4, 6}}
Diff

Returns the elements in the first collection that are not in the second collection.

result := col.Diff([]int{1, 2, 3, 4}, []int{2, 4})
// result: []int{1, 3}
DiffAssoc

Returns the key-value pairs in the first map that are not in the second map.

result := col.DiffAssoc(
    map[string]int{"a": 1, "b": 2, "c": 3},
    map[string]int{"b": 2, "c": 4, "d": 5},
)
// result: map[string]int{"a": 1, "c": 3}
DiffKeys

Returns the key-value pairs in the first map whose keys are not in the second map.

result := col.DiffKeys(
    map[string]int{"a": 1, "b": 2, "c": 3},
    map[string]int{"b": 20, "d": 40},
)
// result: map[string]int{"a": 1, "c": 3}
Except

Returns a map without the specified keys.

result := col.Except(
    map[string]int{"a": 1, "b": 2, "c": 3},
    []string{"a", "c"},
)
// result: map[string]int{"b": 2}
First

Returns the first element in a collection that satisfies a predicate.

result, ok := col.First([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: 2, ok: true

result, ok := col.First([]int{1, 3, 5}, func(n int) bool { 
    return n%2 == 0 
})
// result: 0, ok: false
FirstOrDefault

Returns the first element in a collection or a default value if the collection is empty.

result := col.FirstOrDefault([]int{1, 2, 3}, 0)
// result: 1

result := col.FirstOrDefault([]int{}, 0)
// result: 0
FlatMap

Maps each element in a collection and then flattens the result.

result := col.FlatMap([]int{1, 2}, func(n int) []int { 
    return []int{n, n * 2} 
})
// result: []int{1, 2, 2, 4}
Flatten

Flattens a collection of collections into a single collection.

result := col.Flatten([][]int{{1, 2}, {3, 4}})
// result: []int{1, 2, 3, 4}
Flip

Swaps the collection's keys with their corresponding values.

result := col.Flip(map[string]int{"a": 1, "b": 2})
// result: map[int]string{1: "a", 2: "b"}
Forget

Removes items from the collection by their keys.

result := col.Forget(
    map[string]int{"a": 1, "b": 2, "c": 3},
    "a", "c",
)
// result: map[string]int{"b": 2}
Get

Retrieves an item from the collection by its key.

result := col.Get(
    map[string]int{"a": 1, "b": 2},
    "a",
    0,
)
// result: 1

result := col.Get(
    map[string]int{"a": 1, "b": 2},
    "c",
    0,
)
// result: 0
Has

Determines if a given key exists in the collection.

result := col.Has(
    map[string]int{"a": 1, "b": 2},
    "a",
)
// result: true

result := col.Has(
    map[string]int{"a": 1, "b": 2},
    "c",
)
// result: false
Implode

Joins the items in a collection into a single string.

result := col.Implode(
    []int{1, 2, 3},
    ", ",
    func(n int) string { return string(rune('0' + n)) },
)
// result: "1, 2, 3"
Intersect

Removes any values from the original collection that are not present in the given array or collection.

result := col.Intersect([]int{1, 2, 3, 4}, []int{2, 4, 6})
// result: []int{2, 4}
IntersectByKeys

Returns a new map containing only the key-value pairs from collection where the key is in the keys slice.

result := col.IntersectByKeys(
    map[string]int{"a": 1, "b": 2, "c": 3},
    []string{"a", "c"},
)
// result: map[string]int{"a": 1, "c": 3}
IsEmpty

Checks if a collection is empty.

result := col.IsEmpty([]int{})
// result: true

result := col.IsEmpty([]int{1, 2, 3})
// result: false
IsNotEmpty

Checks if a collection is not empty.

result := col.IsNotEmpty([]int{1, 2, 3})
// result: true

result := col.IsNotEmpty([]int{})
// result: false
Keys

Returns the keys of a map.

result := col.Keys(map[string]int{"a": 1, "b": 2})
// result: []string{"a", "b"} (order may vary)
Last

Returns the last element in a collection that satisfies a predicate.

result, ok := col.Last([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: 4, ok: true

result, ok := col.Last([]int{1, 3, 5}, func(n int) bool { 
    return n%2 == 0 
})
// result: 0, ok: false
LastOrDefault

Returns the last element in a collection or a default value if the collection is empty.

Parameters:

  • collection: The slice to process
  • defaultValue: The value to return if the collection is empty

Returns:

  • T: The last element in the collection or the default value if the collection is empty
result := col.LastOrDefault([]int{1, 2, 3}, 0)
// result: 3

result := col.LastOrDefault([]int{}, 0)
// result: 0
Max

Returns the maximum value in a collection.

Parameters:

  • collection: The slice to process
  • valueFunc: The function that extracts a numeric value from each element

Returns:

  • V: The maximum value found, or zero if the collection is empty
result := col.Max([]int{1, 2, 3, 4}, func(n int) int { 
    return n 
})
// result: 4

result := col.Max([]struct{Age int}{{Age: 25}, {Age: 30}, {Age: 20}}, func(p struct{Age int}) int { return p.Age })
// result: 30
Merge

Merges the given array or collection with the original collection. If a key exists in both collections, the value from items will be used.

Parameters:

  • collection: The base map to merge into
  • items: The map to merge from

Returns:

  • map[K]V: A new map containing all key-value pairs from both maps, with items taking precedence for duplicate keys
result := col.Merge(
    map[string]int{"a": 1, "b": 2},
    map[string]int{"b": 3, "c": 4},
)
// result: map[string]int{"a": 1, "b": 3, "c": 4}
Min

Returns the minimum value in a collection.

Parameters:

  • collection: The slice to process
  • valueFunc: The function that extracts a numeric value from each element

Returns:

  • V: The minimum value found, or zero if the collection is empty
result := col.Min([]int{1, 2, 3, 4}, func(n int) int { 
    return n 
})
// result: 1

result := col.Min([]struct{Age int}{{Age: 25}, {Age: 30}, {Age: 20}}, func(p struct{Age int}) int { return p.Age })
// result: 20
Only

Returns the items in the collection with the specified keys.

Parameters:

  • collection: The map to filter
  • keys: The keys to keep in the result

Returns:

  • map[K]V: A new map containing only the key-value pairs from collection where the key is in the keys slice
result := col.Only(
    map[string]int{"a": 1, "b": 2, "c": 3},
    []string{"a", "c"},
)
// result: map[string]int{"a": 1, "c": 3}
Pad

Pads a collection to the specified size with a given value. If the size is less than or equal to the length of the collection, it returns the original collection.

Parameters:

  • collection: The slice to pad
  • size: The desired size of the resulting slice
  • value: The value to use for padding

Returns:

  • A new slice padded to the specified size with the given value, or the original slice if size is less than or equal to the length of the collection
result := col.Pad([]int{1, 2, 3}, 5, 0)
// result: []int{1, 2, 3, 0, 0}

result := col.Pad([]int{1, 2, 3}, 2, 0)
// result: []int{1, 2, 3}
Pluck

Retrieves all of the values for a given key from each element in a collection.

Parameters:

  • collection: The slice to process
  • key: The function that extracts a value from each element

Returns:

  • A new slice containing the values extracted from each element in the collection
type User struct {
    Name string
    Age  int
}

users := []User{
    {Name: "Alice", Age: 30},
    {Name: "Bob", Age: 25},
}

result := col.Pluck(users, func(u User) string { 
    return u.Name 
})
// result: []string{"Alice", "Bob"}
Prepend

Adds items to the beginning of the collection.

Parameters:

  • collection: The slice to prepend to
  • values: The values to add to the beginning of the collection

Returns:

  • A new slice with the values prepended to the collection
result := col.Prepend([]int{3, 4}, 1, 2)
// result: []int{1, 2, 3, 4}
Pull

Removes and returns an item from the collection by key.

Parameters:

  • collection: The slice to remove an item from
  • index: The index of the item to remove

Returns:

  • The removed item
  • A new slice with the item removed
element, result := col.Pull([]int{1, 2, 3, 4}, 1)
// element: 2, result: []int{1, 3, 4}
Push

Adds items to the end of the collection.

Parameters:

  • collection: The slice to append to
  • values: The values to add to the end of the collection

Returns:

  • A new slice with the values appended to the collection
result := col.Push([]int{1, 2}, 3, 4)
// result: []int{1, 2, 3, 4}
Put

Adds a key-value pair to a map.

Parameters:

  • collection: The map to add the key-value pair to
  • key: The key to set
  • value: The value to set

Returns:

  • map[K]V: A new map with the key-value pair added or updated
result := col.Put(
    map[string]int{"a": 1, "b": 2},
    "c",
    3,
)
// result: map[string]int{"a": 1, "b": 2, "c": 3}
Random

Returns a random element from a collection.

Parameters:

  • collection: The slice to get a random item from

Returns:

  • T: A random item from the collection
  • bool: True if an item was returned, false if the collection is empty
result, ok := col.Random([]int{1, 2, 3, 4})
// result: a random element from the collection, ok: true

result, ok := col.Random([]int{})
// result: 0, ok: false
RandomOrDefault

Returns a random element from a collection or a default value if the collection is empty.

Parameters:

  • collection: The slice to get a random element from
  • defaultValue: The value to return if the collection is empty

Returns:

  • T: A random element from the collection or the default value if the collection is empty
result := col.RandomOrDefault([]int{1, 2, 3, 4}, 0)
// result: a random element from the collection

result := col.RandomOrDefault([]int{}, 0)
// result: 0

Searches the collection for a given value and returns the corresponding index if successful.

Parameters:

  • collection: The slice to search in
  • value: The value to search for

Returns:

  • int: The index of the found element, or -1 if not found
  • bool: True if the element was found, false otherwise
index, ok := col.Search([]int{1, 2, 3, 4}, 3)
// index: 2, ok: true

index, ok := col.Search([]int{1, 2, 3, 4}, 5)
// index: -1, ok: false
SearchFunc

Searches the collection using the given predicate function and returns the index of the first matching element.

Parameters:

  • collection: The slice to search in
  • predicate: The function that returns true for the element to find

Returns:

  • int: The index of the first element that satisfies the predicate, or -1 if not found
  • bool: True if an element was found, false otherwise
index, ok := col.SearchFunc([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 && n > 2 
})
// index: 3, ok: true

index, ok := col.SearchFunc([]int{1, 2, 3, 4}, func(n int) bool { 
    return n > 4 
})
// index: -1, ok: false
Shift

Removes the first element from a collection and returns it.

Parameters:

  • collection: The slice to remove the first element from

Returns:

  • T: The first element of the collection, or zero value if the collection is empty
  • []T: The remaining elements of the collection
element, result := col.Shift([]int{1, 2, 3, 4})
// element: 1, result: []int{2, 3, 4}

element, result := col.Shift([]int{})
// element: 0, result: []int{}
Sort

Sorts a collection using a comparison function.

Parameters:

  • collection: The slice to sort
  • less: The comparison function that defines the sort order. Should return true if the first argument should be ordered before the second.

Returns:

  • []T: A new sorted slice
result := col.Sort([]int{4, 2, 1, 3}, func(a, b int) bool { 
    return a < b 
})
// result: []int{1, 2, 3, 4}

result := col.Sort([]int{3, 1, 4, 2}, func(a, b int) bool { 
    return a > b 
})
// result: []int{4, 3, 2, 1}
SortByDesc

Sorts a collection in descending order based on a key generated by an iteratee function.

Parameters:

  • collection: The slice to process
  • keyFunc: The function that returns the value to sort by
  • less: The comparison function that defines the sort order. Should return true if the first argument should be ordered before the second.

Returns:

  • []T: A new slice sorted in descending order by the extracted keys
result := col.SortByDesc([]int{1, 2, 3, 4}, func(n int) int { 
    return n 
}, func(a, b int) bool { 
    return a < b 
})
// result: []int{4, 3, 2, 1}

// Sort strings in descending order
result := col.SortByDesc([]string{"a", "c", "b"}, func(s string) string { 
    return s 
}, func(a, b string) bool { 
    return a < b 
})
// result: []string{"c", "b", "a"}
Splice

Removes and returns a slice of elements from the collection starting at the given index.

Parameters:

  • collection: The slice to modify
  • start: The starting index (can be negative to count from the end)
  • length: The number of elements to remove

Returns:

  • []T: A slice containing the removed elements
  • []T: The modified collection with elements removed
removed, result := col.Splice([]int{1, 2, 3, 4}, 1, 2)
// removed: []int{2, 3}, result: []int{1, 4}

removed, result := col.Splice([]int{1, 2, 3}, -1, 1)
// removed: []int{3}, result: []int{1, 2}

removed, result := col.Splice([]int{1, 2, 3}, 5, 1)
// removed: []int{}, result: []int{1, 2, 3}
Split

Breaks a collection into the given number of groups.

Parameters:

  • collection: The slice to split
  • numberOfGroups: The number of groups to split the collection into

Returns:

  • [][]T: A slice of slices, where each inner slice contains elements distributed evenly
result := col.Split([]int{1, 2, 3, 4, 5, 6}, 3)
// result: [][]int{{1, 4}, {2, 5}, {3, 6}}

result := col.Split([]int{1, 2, 3, 4, 5}, 2)
// result: [][]int{{1, 3, 5}, {2, 4}}

result := col.Split([]int{}, 3)
// result: [][]int{}
Sum

Returns the sum of all items in the collection.

Parameters:

  • collection: The slice to sum
  • valueFunc: The function that extracts a numeric value from each element

Returns:

  • V: The sum of all values extracted from the collection
result := col.Sum([]int{1, 2, 3, 4}, func(n int) int { 
    return n 
})
// result: 10

result := col.Sum([]int{1, 2, 3}, func(n int) int { 
    return n * 2 
})
// result: 12

result := col.Sum([]struct{Value int}{{1}, {2}}, func(x struct{Value int}) int { 
    return x.Value 
})
// result: 3
Take

Takes the first n elements from a collection.

Parameters:

  • collection: The slice to extract elements from
  • limit: The number of elements to take from the beginning of the collection

Returns:

  • []T: A new slice containing the first n elements, or the entire collection if n is greater than the collection length
result := col.Take([]int{1, 2, 3, 4}, 2)
// result: []int{1, 2}

result := col.Take([]int{1, 2, 3}, 5)
// result: []int{1, 2, 3}

result := col.Take([]int{1, 2, 3}, 0)
// result: []int{}
Tap

Passes a collection to a callback and returns the collection. This is useful for performing side effects on a collection while maintaining a fluent interface.

Parameters:

  • collection: The slice to pass to the callback
  • callback: The function to call with the collection

Returns:

  • []T: The original collection (which may be modified by the callback)
sum := 0
result := col.Tap([]int{1, 2, 3, 4}, func(arr []int) {
    for _, n := range arr {
        sum += n
    }
})
// sum: 10, result: []int{1, 2, 3, 4}

nums := []int{1, 2}
result := col.Tap(nums, func(x []int) { 
    x[0] = 99 
})
// result: []int{99, 2}
Unique

Returns all of the unique items in the collection.

Parameters:

  • collection: The slice to remove duplicates from

Returns:

  • []T: A new slice containing only unique elements, preserving the original order of first occurrence
result := col.Unique([]int{1, 2, 2, 3, 3, 3, 4})
// result: []int{1, 2, 3, 4}

result := col.Unique([]string{"a", "a", "b", "c"})
// result: []string{"a", "b", "c"}
UniqueBy

Returns all of the unique items in the collection using the given key function.

Parameters:

  • collection: The slice to remove duplicates from
  • keyFunc: The function that extracts the key to determine uniqueness

Returns:

  • []T: A new slice containing only elements with unique keys, preserving the original order of first occurrence
type User struct {
    ID   int
    Name string
}

users := []User{
    {ID: 1, Name: "Alice"},
    {ID: 2, Name: "Bob"},
    {ID: 1, Name: "Charlie"},
}

result := col.UniqueBy(users, func(u User) int { 
    return u.ID 
})
// result: []User{{ID: 1, Name: "Alice"}, {ID: 2, Name: "Bob"}}

result := col.UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(n int) int { return n % 3 })
// Returns: []int{1, 2, 3} (because 1%3=1, 2%3=2, 3%3=0, 4%3=1, 5%3=2, 6%3=0)
Values

Returns the values of a map.

result := col.Values(map[string]int{"a": 1, "b": 2})
// result: []int{1, 2} (order may vary)
Zip

Combines multiple collections into a collection of collections.

Parameters:

  • collection: The base slice to merge with other arrays
  • arrays: Variable number of slices to merge with the collection

Returns:

  • [][]T: A new slice of slices where each inner slice contains elements from the same position across all input slices
result := col.Zip([]int{1, 2}, []int{3, 4}, []int{5, 6})
// result: [][]int{{1, 3, 5}, {2, 4, 6}}

result := col.Zip([]string{"a", "b"}, []string{"c", "d"})
// result: [][]string{{"a", "c"}, {"b", "d"}}
Unless

Executes the given callback when the condition is false.

Parameters:

  • condition: The boolean condition to check
  • collection: The slice to pass to the callback if the condition is false
  • callback: The function to call with the collection if the condition is false

Returns:

  • []T: The result of the callback if the condition is false, otherwise the original collection
result := col.Unless(false, []int{1, 2, 3}, func(arr []int) []int {
    return col.Map(arr, func(n int) int { return n * 2 })
})
// result: []int{2, 4, 6} (because condition is false)

result := col.Unless(true, []int{1, 2, 3}, func(arr []int) []int {
    return col.Map(arr, func(n int) int { return n * 2 })
})
// result: []int{1, 2, 3} (because condition is true)

result := col.Unless(false, []int{1, 2, 3}, func(x []int) []int { 
    return append(x, 4) 
})
// result: []int{1, 2, 3, 4} (because condition is false)
UnlessEmpty

Executes the given callback when the collection is not empty.

Parameters:

  • collection: The slice to check and pass to the callback if not empty
  • callback: The function to call with the collection if it's not empty

Returns:

  • []T: The result of the callback if the collection is not empty, otherwise the original collection
result := col.UnlessEmpty([]int{1, 2, 3}, func(x []int) []int { 
    return append(x, 4) 
})
// result: []int{1, 2, 3, 4} (because collection is not empty)

result := col.UnlessEmpty([]int{}, func(x []int) []int { 
    return append(x, 1) 
})
// result: []int{} (because collection is empty)
UnlessNotEmpty

Executes the given callback when the collection is empty.

Parameters:

  • collection: The slice to check and pass to the callback if empty
  • callback: The function to call with the collection if it's empty

Returns:

  • []T: The result of the callback if the collection is empty, otherwise the original collection
result := col.UnlessNotEmpty([]int{1, 2, 3}, func(x []int) []int { 
    return append(x, 4) 
})
// result: []int{1, 2, 3} (because collection is not empty)

result := col.UnlessNotEmpty([]int{}, func(x []int) []int { 
    return append(x, 1) 
})
// result: []int{1} (because collection is empty)
Values

Returns all of the values in the map collection.

Parameters:

  • collection: The map to extract values from

Returns:

  • []V: A slice containing all values from the map
result := col.Values(map[string]int{"a": 1, "b": 2, "c": 3})
// result: []int{1, 2, 3}

result := col.Values(map[string]int{})
// result: []int{}
When

Executes the given callback when the condition is true.

Parameters:

  • condition: The boolean condition to check
  • collection: The slice to pass to the callback if the condition is true
  • callback: The function to call with the collection if the condition is true

Returns:

  • []T: The result of the callback if the condition is true, otherwise the original collection
result := col.When(true, []int{1, 2, 3}, func(arr []int) []int {
    return col.Map(arr, func(n int) int { return n * 2 })
})
// result: []int{2, 4, 6} (because condition is true)

result := col.When(false, []int{1, 2, 3}, func(arr []int) []int {
    return col.Map(arr, func(n int) int { return n * 2 })
})
// result: []int{1, 2, 3} (because condition is false)

result := col.When(true, []int{1, 2, 3}, func(x []int) []int { 
    return append(x, 4) 
})
// result: []int{1, 2, 3, 4} (because condition is true)
WhenEmpty

Executes the given callback when the collection is empty.

Parameters:

  • collection: The slice to check and pass to the callback if empty
  • callback: The function to call with the collection if it's empty

Returns:

  • []T: The result of the callback if the collection is empty, otherwise the original collection
result := col.WhenEmpty([]int{}, func(x []int) []int { 
    return append(x, 1) 
})
// result: []int{1} (because collection is empty)

result := col.WhenEmpty([]int{1, 2, 3}, func(x []int) []int { 
    return append(x, 4) 
})
// result: []int{1, 2, 3} (because collection is not empty)
WhenNotEmpty

Executes the given callback when the collection is not empty.

Parameters:

  • collection: The slice to check and pass to the callback if not empty
  • callback: The function to call with the collection if it's not empty

Returns:

  • []T: The result of the callback if the collection is not empty, otherwise the original collection
result := col.WhenNotEmpty([]int{1, 2, 3}, func(x []int) []int { 
    return append(x, 4) 
})
// result: []int{1, 2, 3, 4} (because collection is not empty)

result := col.WhenNotEmpty([]int{}, func(x []int) []int { 
    return append(x, 1) 
})
// result: []int{} (because collection is empty)
Where

Filters elements in a collection based on a predicate.

Parameters:

  • collection: The slice to filter
  • predicate: The function that determines whether an element should be included in the result

Returns:

  • []T: A new slice containing only the elements that satisfy the predicate
result := col.Where([]int{1, 2, 3, 4}, func(n int) bool { 
    return n%2 == 0 
})
// result: []int{2, 4}

result := col.Where([]int{1, 3, 5}, func(n int) bool { 
    return n%2 == 0 
})
// result: []int{}
WhereIn

Filters elements in a collection whose key is in a list of values.

Parameters:

  • collection: The slice to filter
  • keyFunc: The function that extracts the key to check against the values
  • values: The slice of values to check against

Returns:

  • []T: A new slice containing only the elements whose extracted keys are in the values slice
type User struct {
    ID   int
    Name string
}

users := []User{
    {ID: 1, Name: "Alice"},
    {ID: 2, Name: "Bob"},
    {ID: 3, Name: "Charlie"},
}

result := col.WhereIn(users, func(u User) int { 
    return u.ID 
}, []int{1, 3})
// result: []User{{ID: 1, Name: "Alice"}, {ID: 3, Name: "Charlie"}}

result := col.WhereIn([]int{1, 2, 3, 4, 5}, func(n int) int { 
    return n % 3 
}, []int{0, 1})
// result: []int{1, 3, 4} (because 1%3=1, 3%3=0, 4%3=1, which are in [0,1])
WhereNotIn

Filters elements in a collection whose key is not in a list of values.

Parameters:

  • collection: The slice to filter
  • keyFunc: The function that extracts the key to check against the values
  • values: The slice of values to check against

Returns:

  • []T: A new slice containing only the elements whose extracted keys are not in the values slice
type User struct {
    ID   int
    Name string
}

users := []User{
    {ID: 1, Name: "Alice"},
    {ID: 2, Name: "Bob"},
    {ID: 3, Name: "Charlie"},
}

result := col.WhereNotIn(users, func(u User) int { 
    return u.ID 
}, []int{1, 3})
// result: []User{{ID: 2, Name: "Bob"}}

result := col.WhereNotIn([]int{1, 2, 3, 4, 5}, func(n int) int { 
    return n % 3 
}, []int{0, 1})
// result: []int{2, 5} (because 2%3=2, 5%3=2, which are not in [0,1])
Function Utilities
After

Creates a function that invokes the provided function once it's called n or more times.

fn := col.After(3, func() string { 
    return "done" 
})
// First two calls return zero value
fn() // returns ""
fn() // returns ""
// Third call invokes the function
fn() // returns "done"
// Subsequent calls also invoke the function
fn() // returns "done"
Before

Creates a function that invokes the provided function at most n times.

count := 0
fn := col.Before(3, func() int { 
    count++
    return count 
})
fn() // returns 1
fn() // returns 2
fn() // returns 3
// Subsequent calls return the last result
fn() // returns 3
fn() // returns 3
Curry

Creates a function that accepts arguments of the provided function and either invokes it (if enough arguments are provided) or returns a function that accepts the remaining arguments.

add := func(a, b int) int { 
    return a + b 
}
addCurried := col.Curry(add, 2)
add1 := addCurried(1)
result := add1(2) // returns 3
Debounce

Creates a debounced function that delays invoking the provided function until after a specified duration has elapsed since the last time the debounced function was invoked.

// This will only execute once, 100ms after the last call
fn := col.Debounce(func() {
    fmt.Println("Function executed")
}, 100*time.Millisecond)

// These rapid calls will be debounced
fn()
fn()
fn() // Only this last call will trigger the function after 100ms

Documentation

Overview

Package col provides utility functions for collection manipulation. In Go, collections can be slices or maps.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Avg

func Avg[T any](collection []T, valueFunc func(T) float64) float64

Avg returns the average value of a collection using the provided value function.

Parameters:

  • collection: The slice to process
  • valueFunc: The function that returns the numeric value for each element

Returns:

  • float64: The average value of the collection

Example:

Avg([]int{1, 2, 3, 4}, func(n int) float64 { return float64(n) })
// Returns: 2.5

func Chunk

func Chunk[T any](collection []T, size int) [][]T

Chunk breaks the collection into multiple, smaller collections of a given size.

Parameters:

  • collection: The slice to chunk
  • size: The size of each chunk

Returns:

  • [][]T: A slice of slices, each of the specified size (except possibly the last one)

Example:

Chunk([]int{1, 2, 3, 4, 5}, 2)
// Returns: [][]int{{1, 2}, {3, 4}, {5}}

func Collapse

func Collapse[T any](collection [][]T) []T

Collapse collapses a collection of arrays into a single, flat collection.

Parameters:

  • collection: The slice of slices to collapse

Returns:

  • []T: A single flattened slice containing all elements from the input slices

Example:

Collapse([][]int{{1, 2}, {3, 4}})
// Returns: []int{1, 2, 3, 4}

func Contains

func Contains[T comparable](collection []T, item T) bool

Contains determines whether the collection contains a given item.

Parameters:

  • collection: The slice to search
  • item: The item to search for

Returns:

  • bool: True if the item is in the collection, false otherwise

Example:

Contains([]int{1, 2, 3}, 2)
// Returns: true

func ContainsFn

func ContainsFn[T any](collection []T, predicate func(T) bool) bool

ContainsFn determines whether the collection contains an item that satisfies the given predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for the element to check

Returns:

  • bool: True if any element satisfies the predicate, false otherwise

Example:

ContainsFn([]int{1, 2, 3}, func(n int) bool { return n > 2 })
// Returns: true

func Count

func Count[T any](collection []T) int

Count returns the total number of items in the collection.

Parameters:

  • collection: The slice to count

Returns:

  • int: The number of elements in the collection

Example:

Count([]int{1, 2, 3})
// Returns: 3

func CountBy

func CountBy[T any, K comparable](collection []T, iteratee func(T) K) map[K]int

CountBy counts elements in a collection based on a key generated by an iteratee function.

Parameters:

  • collection: The slice to process
  • iteratee: The function that returns a key for each element

Returns:

  • map[K]int: A map where keys are the result of iteratee and values are the count of elements

Example:

CountBy([]int{1, 2, 3, 4}, func(n int) string {
    if n % 2 == 0 {
        return "even"
    }
    return "odd"
})
// Returns: map[string]int{"odd": 2, "even": 2}

func CrossJoin

func CrossJoin[T any](collection []T, arrays ...[]T) [][]T

CrossJoin cross joins the collection with the given arrays or collections.

Parameters:

  • collection: The base slice to cross join
  • arrays: Variable number of slices to cross join with the collection

Returns:

  • [][]T: A new slice containing all possible combinations of items from the collection and arrays

Example:

CrossJoin([]int{1, 2}, []int{3, 4})
// Returns: [][]int{{1, 3}, {1, 4}, {2, 3}, {2, 4}}

func Diff

func Diff[T comparable](collection, items []T) []T

Diff compares the collection against another collection or array and returns the values in the collection that are not present in the given items.

Parameters:

  • collection: The base slice to compare
  • items: The slice to compare against

Returns:

  • []T: A new slice containing the values from collection that are not present in items

Example:

Diff([]int{1, 2, 3}, []int{2, 3, 4})
// Returns: []int{1}

func DiffAssoc

func DiffAssoc[K comparable, V comparable](collection, items map[K]V) map[K]V

DiffAssoc compares the collection against another collection or array based on its keys and values. Returns the key-value pairs in the collection that are not present in the given items or have different values.

Parameters:

  • collection: The base map to compare
  • items: The map to compare against

Returns:

  • map[K]V: A new map containing the key-value pairs from collection that are not present in items or have different values

Example:

DiffAssoc(map[string]int{"a": 1, "b": 2}, map[string]int{"a": 1, "b": 3})
// Returns: map[string]int{"b": 2}

func DiffKeys

func DiffKeys[K comparable, V any](collection, items map[K]V) map[K]V

DiffKeys compares the collection against another collection or array based on its keys. Returns the key-value pairs in the collection where the keys are not present in the given items.

Parameters:

  • collection: The base map to compare
  • items: The map to compare against

Returns:

  • map[K]V: A new map containing the key-value pairs from collection where the keys are not present in items

Example:

DiffKeys(map[string]int{"a": 1, "b": 2}, map[string]int{"a": 3})
// Returns: map[string]int{"b": 2}

func Each

func Each[T any](collection []T, callback func(T, int) bool)

Each iterates over the collection and passes each item to the given callback. The iteration stops if the callback returns false.

Parameters:

  • collection: The slice to iterate over
  • callback: The function to call for each element, receives the element and its index. Return false to stop iteration, true to continue.

Returns:

  • None: This function doesn't return anything

Example:

Each([]int{1, 2, 3}, func(n int, i int) bool {
    fmt.Println(n)
    return true // continue iteration
})
// Prints: 1, 2, 3

func Every

func Every[T any](collection []T, predicate func(T) bool) bool

Every checks if all elements in the collection satisfy the predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for elements to include

Returns:

  • bool: True if all elements satisfy the predicate, false otherwise

Example:

Every([]int{2, 4, 6}, func(n int) bool { return n % 2 == 0 })
// Returns: true

func Except

func Except[K comparable, V any](collection map[K]V, keys []K) map[K]V

Except returns all items in the collection except for those with the specified keys.

Parameters:

  • collection: The map to filter
  • keys: The keys to exclude from the result

Returns:

  • map[K]V: A new map containing all key-value pairs from collection except those with keys in the keys slice

Example:

Except(map[string]int{"a": 1, "b": 2, "c": 3}, []string{"a", "c"})
// Returns: map[string]int{"b": 2}

func Filter

func Filter[T any](collection []T, predicate func(T) bool) []T

Filter filters elements of a collection that satisfy the predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for elements to include

Returns:

  • []T: A new slice containing only the elements that satisfy the predicate

Example:

Filter([]int{1, 2, 3, 4}, func(n int) bool { return n % 2 == 0 })
// Returns: []int{2, 4}

func FilterMap

func FilterMap[K comparable, V any](collection map[K]V, predicate func(V, K) bool) map[K]V

FilterMap filters elements of a map that satisfy the predicate. This function creates a new map containing only the key-value pairs for which the predicate function returns true. The original map is not modified.

Parameters:

  • collection: The map to process
  • predicate: The function that returns true for elements to include

Returns:

  • map[K]V: A new map containing only the elements that satisfy the predicate

Example:

// Filter values greater than 1
FilterMap(map[string]int{"a": 1, "b": 2, "c": 3}, func(v int, k string) bool {
    return v > 1
})
// Returns: map[string]int{"b": 2, "c": 3}

// Filter keys that start with "a"
FilterMap(map[string]int{"a": 1, "b": 2, "apple": 3}, func(v int, k string) bool {
    return strings.HasPrefix(k, "a")
})
// Returns: map[string]int{"a": 1, "apple": 3}

func Find

func Find[T any](collection []T, predicate func(T) bool) (T, bool)

Find finds the first element in the collection that satisfies the predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for the element to find

Returns:

  • T: The first element that satisfies the predicate
  • bool: True if an element was found, false otherwise

Example:

Find([]int{1, 2, 3, 4}, func(n int) bool { return n > 2 })
// Returns: 3, true

func FindLast

func FindLast[T any](collection []T, predicate func(T) bool) (T, bool)

FindLast returns the last element in a collection that satisfies a predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for the element to find

Returns:

  • T: The last element that satisfies the predicate
  • bool: True if an element was found, false otherwise

Example:

result, ok := FindLast([]int{1, 2, 3, 4}, func(n int) bool {
    return n%2 == 0
})
// Returns: 4, true

result, ok := FindLast([]int{1, 3, 5}, func(n int) bool {
    return n%2 == 0
})
// Returns: 0, ok: false

func First

func First[T any](collection []T, predicate func(T) bool) (T, bool)

First returns the first element in the collection that passes a given truth test.

Parameters:

  • collection: The slice to search
  • predicate: The function that returns true for the element to find

Returns:

  • T: The first element that satisfies the predicate
  • bool: True if an element was found, false otherwise

Example:

First([]int{1, 2, 3, 4}, func(n int) bool { return n > 2 })
// Returns: 3, true

func FirstOrDefault

func FirstOrDefault[T any](collection []T, defaultValue T) T

FirstOrDefault returns the first element in the collection or a default value if the collection is empty.

Parameters:

  • collection: The slice to get the first element from
  • defaultValue: The value to return if the collection is empty

Returns:

  • T: The first element in the collection or the default value if the collection is empty

Example:

FirstOrDefault([]int{}, 0)
// Returns: 0

FirstOrDefault([]int{1, 2, 3}, 0)
// Returns: 1

func FlatMap

func FlatMap[T any, R any](collection []T, callback func(T) []R) []R

FlatMap iterates through the collection and passes each value to the given callback. The callback should return a slice, and all slices are flattened into a single result slice.

Parameters:

  • collection: The slice to process
  • callback: The function that maps each element to a slice of elements

Returns:

  • []R: A new slice containing all elements from the slices returned by the callback

Example:

FlatMap([]int{1, 2}, func(n int) []int { return []int{n, n * 2} })
// Returns: []int{1, 2, 2, 4}

func Flatten

func Flatten[T any](collection [][]T) []T

Flatten flattens a multi-dimensional collection into a single dimension.

Parameters:

  • collection: The slice of slices to flatten

Returns:

  • []T: A new slice containing all elements from all slices in the collection

Example:

Flatten([][]int{{1, 2}, {3, 4}})
// Returns: []int{1, 2, 3, 4}

func Flip

func Flip[K comparable, V comparable](collection map[K]V) map[V]K

Flip swaps the collection's keys with their corresponding values.

Parameters:

  • collection: The map whose keys and values will be swapped

Returns:

  • map[V]K: A new map where the keys are the values from the original map and the values are the keys from the original map

Example:

Flip(map[string]int{"a": 1, "b": 2})
// Returns: map[int]string{1: "a", 2: "b"}

func ForEach

func ForEach[T any](collection []T, iteratee func(T))

ForEach iterates over elements in a collection and applies an iteratee function.

Parameters:

  • collection: The slice to process
  • iteratee: The function to invoke for each element

Example:

sum := 0
ForEach([]int{1, 2, 3, 4}, func(n int) {
    sum += n
})
// sum: 10

func ForEachMap

func ForEachMap[K comparable, V any](collection map[K]V, iteratee func(V, K))

ForEachMap iterates over elements of a map and invokes iteratee for each element. This function is useful for performing side effects on each element of a map without creating a new collection. The order of iteration is not guaranteed due to the nature of Go maps.

Parameters:

  • collection: The map to process
  • iteratee: The function to invoke for each element with its key

Returns:

  • None

Example:

// Print each key-value pair
ForEachMap(map[string]int{"a": 1, "b": 2}, func(v int, k string) {
    fmt.Println(k, v)
})
// Prints: a 1, b 2 (order may vary)

// Calculate sum of values
sum := 0
ForEachMap(map[string]int{"a": 1, "b": 2, "c": 3}, func(v int, k string) {
    sum += v
})
// sum: 6

func ForEachWithIndex

func ForEachWithIndex[T any](collection []T, iteratee func(T, int))

ForEachWithIndex is like ForEach, but the iteratee function also receives the index of the element.

Parameters:

  • collection: The slice to process
  • iteratee: The function to invoke for each element with its index

Example:

sum := 0
ForEachWithIndex([]int{1, 2, 3, 4}, func(n int, i int) {
    sum += n * i
})
// sum: 20

func Forget

func Forget[K comparable, V any](collection map[K]V, keys ...K) map[K]V

Forget removes items from the collection by their keys.

Parameters:

  • collection: The map to remove items from
  • keys: The keys of the items to remove

Returns:

  • map[K]V: A new map containing all key-value pairs from collection except those with keys in the keys parameter

Example:

Forget(map[string]int{"a": 1, "b": 2, "c": 3}, "a", "c")
// Returns: map[string]int{"b": 2}

func Get

func Get[K comparable, V any](collection map[K]V, key K, defaultValue V) V

Get retrieves an item from the collection by its key.

Parameters:

  • collection: The map to get the value from
  • key: The key to look up
  • defaultValue: The value to return if the key doesn't exist in the collection

Returns:

  • V: The value associated with the key, or the default value if the key doesn't exist

Example:

Get(map[string]int{"a": 1, "b": 2}, "a", 0)
// Returns: 1

Get(map[string]int{"a": 1}, "c", 0)
// Returns: 0

func GroupBy

func GroupBy[T any, K comparable](collection []T, iteratee func(T) K) map[K][]T

GroupBy groups elements in a collection based on a key generated by an iteratee function.

Parameters:

  • collection: The slice to process
  • iteratee: The function that returns the key to group by

Returns:

  • map[K][]T: A map where keys are the values returned by iteratee and values are slices of elements

Example:

result := GroupBy([]int{1, 2, 3, 4}, func(n int) string {
    if n%2 == 0 {
        return "even"
    }
    return "odd"
})
// Returns: map[string][]int{"odd": {1, 3}, "even": {2, 4}}

func Has

func Has[K comparable, V any](collection map[K]V, key K) bool

Has determines if a given key exists in the collection.

Parameters:

  • collection: The map to check
  • key: The key to look for

Returns:

  • bool: True if the key exists in the collection, false otherwise

Example:

Has(map[string]int{"a": 1, "b": 2}, "a")
// Returns: true

Has(map[string]int{"a": 1, "b": 2}, "c")
// Returns: false

func Implode

func Implode[T any](collection []T, separator string, toString func(T) string) string

Implode joins the items in a collection into a single string.

Parameters:

  • collection: The slice to join
  • separator: The string to place between elements
  • toString: A function that converts each element to a string

Returns:

  • string: A string containing all elements joined by the separator

Example:

Implode([]int{1, 2, 3}, ", ", func(n int) string { return strconv.Itoa(n) })
// Returns: "1, 2, 3"

func Includes

func Includes[T comparable](collection []T, value T) bool

Includes checks if a collection includes a specific value.

Parameters:

  • collection: The slice to process
  • value: The value to check for

Returns:

  • bool: True if the value is in the collection, false otherwise

Example:

result := Includes([]int{1, 2, 3, 4}, 3)
// Returns: true

result := Includes([]int{1, 2, 3, 4}, 5)
// Returns: false

func Intersect

func Intersect[T comparable](collection, items []T) []T

Intersect removes any values from the original collection that are not present in the given array or collection.

Parameters:

  • collection: The base slice to filter
  • items: The slice to compare against

Returns:

  • []T: A new slice containing only the elements that are present in both collection and items

Example:

Intersect([]int{1, 2, 3}, []int{2, 3, 4})
// Returns: []int{2, 3}

func IntersectByKeys

func IntersectByKeys[K comparable, V any](collection map[K]V, keys []K) map[K]V

IntersectByKeys removes any keys from the original collection that are not present in the given array or collection.

Parameters:

  • collection: The base map to filter
  • keys: The slice of keys to keep

Returns:

  • map[K]V: A new map containing only the key-value pairs from collection where the key is in the keys slice

Example:

IntersectByKeys(map[string]int{"a": 1, "b": 2, "c": 3}, []string{"a", "c"})
// Returns: map[string]int{"a": 1, "c": 3}

func IsEmpty

func IsEmpty[T any](collection []T) bool

IsEmpty determines if the collection is empty.

Parameters:

  • collection: The slice to check

Returns:

  • bool: True if the collection is empty, false otherwise

Example:

IsEmpty([]int{})
// Returns: true

IsEmpty([]int{1, 2})
// Returns: false

func IsNotEmpty

func IsNotEmpty[T any](collection []T) bool

IsNotEmpty determines if the collection is not empty.

Parameters:

  • collection: The slice to check

Returns:

  • bool: True if the collection is not empty, false otherwise

Example:

IsNotEmpty([]int{1, 2})
// Returns: true

IsNotEmpty([]int{})
// Returns: false

func KeyBy

func KeyBy[T any, K comparable](collection []T, iteratee func(T) K) map[K]T

KeyBy creates an object composed of keys generated from the results of running each element of collection through iteratee.

Parameters:

  • collection: The slice to process
  • iteratee: The function that returns the key for each element

Returns:

  • map[K]T: A map where keys are the values returned by iteratee and values are the original elements

Example:

type User struct {
    ID int
    Name string
}
users := []User{{1, "Alice"}, {2, "Bob"}}
KeyBy(users, func(u User) int { return u.ID })
// Returns: map[int]User{1: {1, "Alice"}, 2: {2, "Bob"}}

func Keys

func Keys[K comparable, V any](collection map[K]V) []K

Keys returns all of the collection's keys.

Parameters:

  • collection: The map to extract keys from

Returns:

  • []K: A slice containing all keys from the collection

Example:

Keys(map[string]int{"a": 1, "b": 2})
// Returns: []string{"a", "b"}

func Last

func Last[T any](collection []T, predicate func(T) bool) (T, bool)

Last returns the last element in the collection that passes a given truth test.

Parameters:

  • collection: The slice to search
  • predicate: The function that returns true for the element to find

Returns:

  • T: The last element that satisfies the predicate
  • bool: True if an element was found, false otherwise

Example:

Last([]int{1, 2, 3, 4}, func(n int) bool { return n < 3 })
// Returns: 2, true

func LastOrDefault

func LastOrDefault[T any](collection []T, defaultValue T) T

LastOrDefault returns the last element in the collection or a default value if the collection is empty.

Parameters:

  • collection: The slice to get the last element from
  • defaultValue: The value to return if the collection is empty

Returns:

  • T: The last element in the collection or the default value if the collection is empty

Example:

LastOrDefault([]int{1, 2, 3}, 0)
// Returns: 3

LastOrDefault([]int{}, 0)
// Returns: 0

func Map

func Map[T any, R any](collection []T, iteratee func(T) R) []R

Map creates an array of values by running each element in collection through iteratee.

Parameters:

  • collection: The slice to process
  • iteratee: The function to transform each element

Returns:

  • []R: A new slice containing the transformed elements

Example:

Map([]int{1, 2, 3}, func(n int) int { return n * 2 })
// Returns: []int{2, 4, 6}

func MapMap

func MapMap[K comparable, V any, R any](collection map[K]V, iteratee func(V, K) R) []R

MapMap creates an array of values by running each element in a map through iteratee. Unlike ForEachMap, this function returns a new slice containing the results of applying the iteratee function to each element. The order of elements in the resulting slice is not guaranteed due to the nature of Go maps.

Parameters:

  • collection: The map to process
  • iteratee: The function to transform each element with its key

Returns:

  • []R: A slice containing the transformed elements

Example:

// Transform map values to strings
MapMap(map[string]int{"a": 1, "b": 2}, func(v int, k string) string {
    return k + strconv.Itoa(v)
})
// Returns: []string{"a1", "b2"} (order may vary)

// Extract just the keys
MapMap(map[string]int{"a": 1, "b": 2}, func(v int, k string) string {
    return k
})
// Returns: []string{"a", "b"} (order may vary)

func MapWithIndex

func MapWithIndex[T any, R any](collection []T, iteratee func(T, int) R) []R

MapWithIndex creates an array of values by running each element in collection through iteratee with its index.

Parameters:

  • collection: The slice to process
  • iteratee: The function to transform each element with its index

Returns:

  • []R: A new slice containing the transformed elements

Example:

MapWithIndex([]int{1, 2, 3}, func(n, i int) int { return n * i })
// Returns: []int{0, 2, 6}

func Max

func Max[T any, V float64 | int | int64 | float32 | int32 | int16 | int8 | uint | uint64 | uint32 | uint16 | uint8](collection []T, valueFunc func(T) V) V

Max returns the maximum value of a given key.

Parameters:

  • collection: The slice to process
  • valueFunc: The function that extracts a numeric value from each element

Returns:

  • V: The maximum value found, or zero if the collection is empty

Example:

Max([]int{1, 2, 3, 4}, func(n int) int { return n })
// Returns: 4

Max([]struct{Age int}{{Age: 25}, {Age: 30}, {Age: 20}}, func(p struct{Age int}) int { return p.Age })
// Returns: 30

func Merge

func Merge[K comparable, V any](collection, items map[K]V) map[K]V

Merge merges the given array or collection with the original collection. If a key exists in both collections, the value from items will be used.

Parameters:

  • collection: The base map to merge into
  • items: The map to merge from

Returns:

  • map[K]V: A new map containing all key-value pairs from both maps, with items taking precedence for duplicate keys

Example:

Merge(map[string]int{"a": 1, "b": 2}, map[string]int{"b": 3, "c": 4})
// Returns: map[string]int{"a": 1, "b": 3, "c": 4}

func Min

func Min[T any, V float64 | int | int64 | float32 | int32 | int16 | int8 | uint | uint64 | uint32 | uint16 | uint8](collection []T, valueFunc func(T) V) V

Min returns the minimum value of a given key.

Parameters:

  • collection: The slice to process
  • valueFunc: The function that extracts a numeric value from each element

Returns:

  • V: The minimum value found, or zero if the collection is empty

Example:

Min([]int{1, 2, 3, 4}, func(n int) int { return n })
// Returns: 1

Min([]struct{Age int}{{Age: 25}, {Age: 30}, {Age: 20}}, func(p struct{Age int}) int { return p.Age })
// Returns: 20

func Only

func Only[K comparable, V any](collection map[K]V, keys []K) map[K]V

Only returns the items in the collection with the specified keys.

Parameters:

  • collection: The map to filter
  • keys: The keys to keep in the result

Returns:

  • map[K]V: A new map containing only the key-value pairs from collection where the key is in the keys slice

Example:

Only(map[string]int{"a": 1, "b": 2, "c": 3}, []string{"a", "c"})
// Returns: map[string]int{"a": 1, "c": 3}

func OrderBy

func OrderBy[T any, U int | int8 | int16 | int32 | int64 | float32 | float64 | string](collection []T, iteratee func(T) U, ascending bool) []T

OrderBy sorts a collection by a single iteratee with specified sort direction. This function provides more control than SortBy by allowing you to specify whether to sort in ascending or descending order. The sort is stable, meaning that elements with the same sort key maintain their relative order from the original collection. This function creates a new slice and does not modify the original collection.

Parameters:

  • collection: The slice to sort
  • iteratee: The function that returns the value to sort by (must return a comparable type)
  • ascending: Whether to sort in ascending (true) or descending (false) order

Returns:

  • []T: A new sorted slice in the specified order

Example:

// Sort numbers in ascending order
OrderBy([]int{4, 2, 1, 3}, func(n int) int { return n }, true)
// Returns: []int{1, 2, 3, 4}

// Sort numbers in descending order
OrderBy([]int{4, 2, 1, 3}, func(n int) int { return n }, false)
// Returns: []int{4, 3, 2, 1}

// Sort users by age in ascending order
type User struct {
    Name string
    Age int
}
users := []User{{Name: "fred", Age: 48}, {Name: "barney", Age: 34}}
OrderBy(users, func(u User) int { return u.Age }, true)
// Returns: []User{{Name: "barney", Age: 34}, {Name: "fred", Age: 48}}

func Pad

func Pad[T any](collection []T, size int, value T) []T

Pad fills the array to the specified size with a value.

Parameters:

  • collection: The slice to pad
  • size: The target size of the resulting slice
  • value: The value to use for padding

Returns:

  • []T: A new slice padded to the specified size with the given value, or the original slice if size is less than or equal to the length of the collection

Example:

Pad([]int{1, 2}, 4, 0)
// Returns: []int{1, 2, 0, 0}

func Partition

func Partition[T any](collection []T, predicate func(T) bool) [][]T

Partition splits a collection into two groups, the first of which contains elements that satisfy the predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for elements to include in the first group

Returns:

  • [][]T: A slice containing two slices: the first with elements that satisfy the predicate, the second with elements that don't satisfy the predicate

Example:

Partition([]int{1, 2, 3, 4}, func(n int) bool { return n % 2 == 0 })
// Returns: [][]int{{2, 4}, {1, 3}}

func Pluck

func Pluck[T any, V any](collection []T, key func(T) V) []V

Pluck retrieves all of the values for a given key.

Parameters:

  • collection: The slice to process
  • key: The function that extracts a value from each element

Returns:

  • []V: A new slice containing the values extracted from each element in the collection

Example:

Pluck([]struct{Name string}{{"Alice"}, {"Bob"}}, func(p struct{Name string}) string { return p.Name })
// Returns: []string{"Alice", "Bob"}

func Prepend

func Prepend[T any](collection []T, values ...T) []T

Prepend adds items to the beginning of the collection.

Parameters:

  • collection: The slice to prepend to
  • values: The values to add to the beginning of the collection

Returns:

  • []T: A new slice with the values prepended to the collection

Example:

Prepend([]int{3, 4}, 1, 2)
// Returns: []int{1, 2, 3, 4}

func Pull

func Pull[T any](collection []T, index int) (T, []T)

Pull removes and returns an item from the collection by key.

Parameters:

  • collection: The slice to remove an item from
  • index: The index of the item to remove

Returns:

  • T: The removed item
  • []T: A new slice with the item removed

Example:

Pull([]int{1, 2, 3}, 1)
// Returns: 2, []int{1, 3}

func Push

func Push[T any](collection []T, values ...T) []T

Push adds items to the end of the collection.

Parameters:

  • collection: The slice to append to
  • values: The values to add to the end of the collection

Returns:

  • []T: A new slice with the values appended to the collection

Example:

Push([]int{1, 2}, 3, 4)
// Returns: []int{1, 2, 3, 4}

func Put

func Put[K comparable, V any](collection map[K]V, key K, value V) map[K]V

Put sets the given key and value in the collection.

Parameters:

  • collection: The map to add the key-value pair to
  • key: The key to set
  • value: The value to set

Returns:

  • map[K]V: A new map with the key-value pair added or updated

Example:

Put(map[string]int{"a": 1}, "b", 2)
// Returns: map[string]int{"a": 1, "b": 2}

func Random

func Random[T any](collection []T) (T, bool)

Random retrieves a random item from the collection.

Parameters:

  • collection: The slice to get a random item from

Returns:

  • T: A random item from the collection
  • bool: True if an item was returned, false if the collection is empty

Example:

Random([]int{1, 2, 3})
// Returns: a random element from the slice, true

func RandomOrDefault

func RandomOrDefault[T any](collection []T, defaultValue T) T

RandomOrDefault retrieves a random item from the collection or a default value if the collection is empty.

Parameters:

  • collection: The slice to get a random element from
  • defaultValue: The value to return if the collection is empty

Returns:

  • T: A random element from the collection or the default value if the collection is empty

Example:

RandomOrDefault([]int{1, 2, 3}, 0)
// Returns: a random element from the slice (e.g., 2)

RandomOrDefault([]int{}, 0)
// Returns: 0 (the default value)

func Reduce

func Reduce[T any, R any](collection []T, iteratee func(R, T) R, accumulator R) R

Reduce reduces a collection to a value by iterating through the collection and applying an accumulator function.

Parameters:

  • collection: The slice to process
  • iteratee: The function to apply to each element with the accumulator
  • accumulator: The initial value of the accumulator

Returns:

  • R: The final accumulated value

Example:

Reduce([]int{1, 2, 3}, func(sum, n int) int { return sum + n }, 0)
// Returns: 6

func ReduceMap

func ReduceMap[K comparable, V any, R any](collection map[K]V, iteratee func(R, V, K) R, accumulator R) R

ReduceMap reduces a map to a value by iterating through the map and applying an accumulator function. This function iterates over each key-value pair in the map and applies the iteratee function to accumulate a single result. The order of iteration is not guaranteed due to the nature of Go maps.

Parameters:

  • collection: The map to process
  • iteratee: The function to apply to each element with the accumulator and key
  • accumulator: The initial value of the accumulator

Returns:

  • R: The final accumulated value

Example:

// Sum all values in the map
ReduceMap(map[string]int{"a": 1, "b": 2, "c": 3}, func(sum int, v int, k string) int {
    return sum + v
}, 0)
// Returns: 6

// Concatenate all keys
ReduceMap(map[string]int{"a": 1, "b": 2, "c": 3}, func(result string, v int, k string) string {
    if result == "" {
        return k
    }
    return result + "," + k
}, "")
// Returns: "a,b,c" (order may vary)

func ReduceRight

func ReduceRight[T any, R any](collection []T, iteratee func(R, T) R, accumulator R) R

ReduceRight reduces a collection to a value by iterating through the collection from right to left.

Parameters:

  • collection: The slice to process
  • iteratee: The function to apply to each element with the accumulator
  • accumulator: The initial value of the accumulator

Returns:

  • R: The final accumulated value

Example:

ReduceRight([]int{1, 2, 3}, func(result, n int) int { return result * 10 + n }, 0)
// Returns: 321

func Reject

func Reject[T any](collection []T, predicate func(T) bool) []T

Reject is the opposite of Filter; it returns elements that don't satisfy the predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for elements to exclude

Returns:

  • []T: A new slice containing only the elements that don't satisfy the predicate

Example:

Reject([]int{1, 2, 3, 4}, func(n int) bool { return n % 2 == 0 })
// Returns: []int{1, 3}

func Reverse

func Reverse[T any](collection []T) []T

Reverse reverses the order of the collection's items.

Parameters:

  • collection: The slice to reverse

Returns:

  • []T: A new slice with the elements in reverse order

Example:

Reverse([]int{1, 2, 3})
// Returns: []int{3, 2, 1}

func Sample

func Sample[T any](collection []T) (T, bool)

Sample gets a random element from a collection.

Parameters:

  • collection: The slice to process

Returns:

  • T: A random element from the collection
  • bool: True if an element was returned, false if the collection was empty

Example:

element, found := Sample([]int{1, 2, 3, 4})
// Returns: a random element from the collection and true

func SampleSize

func SampleSize[T any](collection []T, n int) []T

SampleSize gets n random elements from a collection.

Parameters:

  • collection: The slice to process
  • n: The number of random elements to return

Returns:

  • []T: A slice containing n random elements from the collection

Example:

SampleSize([]int{1, 2, 3, 4}, 2)
// Returns: []int{3, 1} (random elements)
func Search[T comparable](collection []T, value T) (int, bool)

Search searches the collection for a given value and returns the corresponding index if successful.

Parameters:

  • collection: The slice to search in
  • value: The value to search for

Returns:

  • int: The index of the found element, or -1 if not found
  • bool: True if the element was found, false otherwise

Example:

Search([]int{1, 2, 3, 4}, 3)
// Returns: 2, true

Search([]int{1, 2, 3, 4}, 5)
// Returns: -1, false

func SearchFunc

func SearchFunc[T any](collection []T, predicate func(T) bool) (int, bool)

SearchFunc searches the collection using the given predicate function and returns the index of the first matching element.

Parameters:

  • collection: The slice to search in
  • predicate: The function that returns true for the element to find

Returns:

  • int: The index of the first element that satisfies the predicate, or -1 if not found
  • bool: True if an element was found, false otherwise

Example:

SearchFunc([]int{1, 2, 3, 4}, func(n int) bool { return n > 2 })
// Returns: 2, true

SearchFunc([]int{1, 2}, func(n int) bool { return n > 2 })
// Returns: -1, false

func Shift

func Shift[T any](collection []T) (T, []T)

Shift removes and returns the first item from the collection.

Parameters:

  • collection: The slice to remove the first element from

Returns:

  • T: The first element of the collection, or zero value if the collection is empty
  • []T: The remaining elements of the collection

Example:

Shift([]int{1, 2, 3})
// Returns: 1, []int{2, 3}

Shift([]int{})
// Returns: 0, []int{}

func Shuffle

func Shuffle[T any](collection []T) []T

Shuffle randomly shuffles the items in the collection.

Parameters:

  • collection: The slice to shuffle

Returns:

  • []T: A new slice with the elements in random order

Example:

Shuffle([]int{1, 2, 3})
// Returns: []int{2, 3, 1} (random order)

Shuffle([]int{})
// Returns: []int{}

func Size

func Size[T any](collection []T) int

Size returns the size of a collection.

Parameters:

  • collection: The slice to measure

Returns:

  • int: The number of elements in the collection

Example:

Size([]int{1, 2, 3})
// Returns: 3

func Slice

func Slice[T any](collection []T, start int) []T

Slice returns a slice of the collection starting at the given index.

Parameters:

  • collection: The slice to extract a portion from
  • start: The starting index (can be negative to count from the end)

Returns:

  • []T: A new slice containing elements from the start index to the end of the collection

Example:

Slice([]int{1, 2, 3, 4}, 1)
// Returns: []int{2, 3, 4}

Slice([]int{1, 2, 3, 4}, -2)
// Returns: []int{3, 4}

Slice([]int{1, 2, 3, 4}, 5)
// Returns: []int{}

func SliceWithLength

func SliceWithLength[T any](collection []T, start, length int) []T

SliceWithLength returns a slice of the collection starting at the given index with the specified length.

Parameters:

  • collection: The slice to extract a portion from
  • start: The starting index (can be negative to count from the end)
  • length: The number of elements to include in the result

Returns:

  • []T: A new slice containing the specified number of elements from the start index

Example:

SliceWithLength([]int{1, 2, 3, 4}, 1, 2)
// Returns: []int{2, 3}

SliceWithLength([]int{1, 2, 3, 4}, -2, 2)
// Returns: []int{3, 4}

SliceWithLength([]int{1, 2, 3, 4}, 0, 10)
// Returns: []int{1, 2, 3, 4}

func Some

func Some[T any](collection []T, predicate func(T) bool) bool

Some checks if any element in the collection satisfies the predicate.

Parameters:

  • collection: The slice to process
  • predicate: The function that returns true for elements to check

Returns:

  • bool: True if any element satisfies the predicate, false otherwise

Example:

Some([]int{1, 2, 3, 4}, func(n int) bool { return n > 3 })
// Returns: true

func Sort

func Sort[T any](collection []T, less func(i, j T) bool) []T

Sort sorts the collection according to the given comparison function.

Parameters:

  • collection: The slice to sort
  • less: The comparison function that defines the sort order. Should return true if the first argument should be ordered before the second.

Returns:

  • []T: A new sorted slice

Example:

Sort([]int{3, 1, 4, 2}, func(i, j int) bool { return i < j })
// Returns: []int{1, 2, 3, 4}

Sort([]int{3, 1, 4, 2}, func(i, j int) bool { return i > j })
// Returns: []int{4, 3, 2, 1}

func SortBy

func SortBy[T any, U int | int8 | int16 | int32 | int64 | float32 | float64 | string](collection []T, iteratee func(T) U) []T

SortBy sorts a collection by the results of running each element through iteratee. The sort is stable, meaning that elements with the same sort key maintain their relative order from the original collection. This function creates a new slice and does not modify the original collection.

Parameters:

  • collection: The slice to sort
  • iteratee: The function that returns the value to sort by (must return a comparable type)

Returns:

  • []T: A new sorted slice in ascending order

Example:

SortBy([]int{1, 3, 2}, func(n int) int { return n })
// Returns: []int{1, 2, 3}

// Sort users by age
users := []User{{Name: "Alice", Age: 30}, {Name: "Bob", Age: 25}}
SortBy(users, func(u User) int { return u.Age })
// Returns: []User{{Name: "Bob", Age: 25}, {Name: "Alice", Age: 30}}

func SortByDesc

func SortByDesc[T any, K comparable](collection []T, keyFunc func(T) K, less func(i, j K) bool) []T

SortByDesc sorts the collection by the given key in descending order.

Parameters:

  • collection: The slice to sort
  • keyFunc: The function that extracts the key to sort by from each element
  • less: The comparison function that defines the sort order. Should return true if the first argument should be ordered before the second.

Returns:

  • []T: A new slice sorted in descending order by the extracted keys

Example:

SortByDesc([]int{3, 1, 4, 2}, func(n int) string { return strconv.Itoa(n) }, func(i, j string) bool { return i < j })
// Returns: []int{4, 3, 2, 1}

SortByDesc([]string{"a", "c", "b"}, func(s string) string { return s }, func(i, j string) bool { return i < j })
// Returns: []string{"c", "b", "a"}

func Splice

func Splice[T any](collection []T, start, length int) ([]T, []T)

Splice removes and returns a slice of elements from the collection starting at the given index.

Parameters:

  • collection: The slice to modify
  • start: The starting index (can be negative to count from the end)
  • length: The number of elements to remove

Returns:

  • []T: A slice containing the removed elements
  • []T: The modified collection with elements removed

Example:

Splice([]int{1, 2, 3, 4}, 1, 2)
// Returns: []int{2, 3}, []int{1, 4}

Splice([]int{1, 2, 3}, -1, 1)
// Returns: []int{3}, []int{1, 2}

Splice([]int{1, 2, 3}, 5, 1)
// Returns: []int{}, []int{1, 2, 3}

func Split

func Split[T any](collection []T, numberOfGroups int) [][]T

Split breaks a collection into the given number of groups.

Parameters:

  • collection: The slice to split
  • numberOfGroups: The number of groups to split the collection into

Returns:

  • [][]T: A slice of slices, where each inner slice contains elements distributed evenly

Example:

Split([]int{1, 2, 3, 4, 5, 6}, 3)
// Returns: [][]int{{1, 4}, {2, 5}, {3, 6}}

Split([]int{1, 2, 3, 4, 5}, 2)
// Returns: [][]int{{1, 3, 5}, {2, 4}}

Split([]int{}, 3)
// Returns: [][]int{}

func Sum

func Sum[T any, V float64 | int | int64 | float32 | int32 | int16 | int8 | uint | uint64 | uint32 | uint16 | uint8](collection []T, valueFunc func(T) V) V

Sum returns the sum of all items in the collection.

Parameters:

  • collection: The slice to sum
  • valueFunc: The function that extracts a numeric value from each element

Returns:

  • V: The sum of all values extracted from the collection

Example:

Sum([]int{1, 2, 3, 4}, func(n int) int { return n })
// Returns: 10

Sum([]int{1, 2, 3}, func(n int) int { return n * 2 })
// Returns: 12

Sum([]struct{Value int}{{1}, {2}}, func(x struct{Value int}) int { return x.Value })
// Returns: 3

func Take

func Take[T any](collection []T, limit int) []T

Take returns a new collection with the specified number of items.

Parameters:

  • collection: The slice to take elements from
  • limit: The maximum number of elements to take

Returns:

  • []T: A new slice containing at most the specified number of elements from the beginning of the collection

Example:

Take([]int{1, 2, 3, 4}, 2)
// Returns: []int{1, 2}

Take([]int{1, 2, 3}, 5)
// Returns: []int{1, 2, 3}

Take([]int{1, 2, 3}, 0)
// Returns: []int{}

func Tap

func Tap[T any](collection []T, callback func([]T)) []T

Tap passes the collection to the given callback then returns the collection.

Parameters:

  • collection: The slice to pass to the callback
  • callback: The function to call with the collection

Returns:

  • []T: The original collection (which may be modified by the callback)

Example:

Tap([]int{1, 2, 3}, func(x []int) { fmt.Println(x) })
// Returns: []int{1, 2, 3} (and prints [1 2 3])

nums := []int{1,2}
Tap(nums, func(x []int) { x[0] = 99 })
// Returns: []int{99, 2}

func Unique

func Unique[T comparable](collection []T) []T

Unique returns all of the unique items in the collection.

Parameters:

  • collection: The slice to remove duplicates from

Returns:

  • []T: A new slice containing only unique elements, preserving the original order of first occurrence

Example:

Unique([]int{1, 2, 2, 3, 3, 3})
// Returns: []int{1, 2, 3}

Unique([]string{"a", "a", "b", "c"})
// Returns: []string{"a", "b", "c"}

func UniqueBy

func UniqueBy[T any, K comparable](collection []T, keyFunc func(T) K) []T

UniqueBy returns all of the unique items in the collection using the given key function.

Parameters:

  • collection: The slice to remove duplicates from
  • keyFunc: The function that extracts the key to determine uniqueness

Returns:

  • []T: A new slice containing only elements with unique keys, preserving the original order of first occurrence

Example:

UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(n int) int { return n % 3 })
// Returns: []int{1, 2, 3} (because 1%3=1, 2%3=2, 3%3=0, 4%3=1, 5%3=2, 6%3=0)

UniqueBy([]string{"one", "two", "three"}, func(s string) int { return len(s) })
// Returns: []string{"one", "three"} (because len("one")=3, len("two")=3, len("three")=5)

func Unless

func Unless[T any](condition bool, collection []T, callback func([]T) []T) []T

Unless executes the given callback when the condition is false.

Parameters:

  • condition: The boolean condition to check
  • collection: The slice to pass to the callback if the condition is false
  • callback: The function to call with the collection if the condition is false

Returns:

  • []T: The result of the callback if the condition is false, otherwise the original collection

Example:

Unless(false, []int{1, 2, 3}, func(x []int) []int { return append(x, 4) })
// Returns: []int{1, 2, 3, 4} (because condition is false)

Unless(true, []int{1, 2, 3}, func(x []int) []int { return append(x, 4) })
// Returns: []int{1, 2, 3} (because condition is true)

func UnlessEmpty

func UnlessEmpty[T any](collection []T, callback func([]T) []T) []T

UnlessEmpty executes the given callback when the collection is not empty.

Parameters:

  • collection: The slice to check and pass to the callback if not empty
  • callback: The function to call with the collection if it's not empty

Returns:

  • []T: The result of the callback if the collection is not empty, otherwise the original collection

Example:

UnlessEmpty([]int{1, 2, 3}, func(x []int) []int { return append(x, 4) })
// Returns: []int{1, 2, 3, 4} (because collection is not empty)

UnlessEmpty([]int{}, func(x []int) []int { return append(x, 1) })
// Returns: []int{} (because collection is empty)

func UnlessNotEmpty

func UnlessNotEmpty[T any](collection []T, callback func([]T) []T) []T

UnlessNotEmpty executes the given callback when the collection is empty.

Parameters:

  • collection: The slice to check and pass to the callback if empty
  • callback: The function to call with the collection if it's empty

Returns:

  • []T: The result of the callback if the collection is empty, otherwise the original collection

Example:

UnlessNotEmpty([]int{1, 2, 3}, func(x []int) []int { return append(x, 4) })
// Returns: []int{1, 2, 3} (because collection is not empty)

UnlessNotEmpty([]int{}, func(x []int) []int { return append(x, 1) })
// Returns: []int{1} (because collection is empty)

func Values

func Values[K comparable, V any](collection map[K]V) []V

Values returns all of the values in the map collection.

Parameters:

  • collection: The map to extract values from

Returns:

  • []V: A slice containing all values from the map

Example:

Values(map[string]int{"a": 1, "b": 2, "c": 3})
// Returns: []int{1, 2, 3}

Values(map[string]int{})
// Returns: []int{}

func When

func When[T any](condition bool, collection []T, callback func([]T) []T) []T

When executes the given callback when the condition is true.

Parameters:

  • condition: The boolean condition to check
  • collection: The slice to pass to the callback if the condition is true
  • callback: The function to call with the collection if the condition is true

Returns:

  • []T: The result of the callback if the condition is true, otherwise the original collection

Example:

When(true, []int{1, 2, 3}, func(x []int) []int { return append(x, 4) })
// Returns: []int{1, 2, 3, 4} (because condition is true)

When(false, []int{1, 2, 3}, func(x []int) []int { return append(x, 4) })
// Returns: []int{1, 2, 3} (because condition is false)

func WhenEmpty

func WhenEmpty[T any](collection []T, callback func([]T) []T) []T

WhenEmpty executes the given callback when the collection is empty.

Parameters:

  • collection: The slice to check and pass to the callback if empty
  • callback: The function to call with the collection if it's empty

Returns:

  • []T: The result of the callback if the collection is empty, otherwise the original collection

Example:

WhenEmpty([]int{}, func(x []int) []int { return append(x, 1) })
// Returns: []int{1} (because collection is empty)

WhenEmpty([]int{1, 2, 3}, func(x []int) []int { return append(x, 4) })
// Returns: []int{1, 2, 3} (because collection is not empty)

func WhenNotEmpty

func WhenNotEmpty[T any](collection []T, callback func([]T) []T) []T

WhenNotEmpty executes the given callback when the collection is not empty.

Parameters:

  • collection: The slice to check and pass to the callback if not empty
  • callback: The function to call with the collection if it's not empty

Returns:

  • []T: The result of the callback if the collection is not empty, otherwise the original collection

Example:

WhenNotEmpty([]int{1, 2, 3}, func(x []int) []int { return append(x, 4) })
// Returns: []int{1, 2, 3, 4} (because collection is not empty)

WhenNotEmpty([]int{}, func(x []int) []int { return append(x, 1) })
// Returns: []int{} (because collection is empty)

func Where

func Where[T any](collection []T, predicate func(T) bool) []T

Where filters the collection using the given predicate function.

Parameters:

  • collection: The slice to filter
  • predicate: The function that determines whether an element should be included in the result

Returns:

  • []T: A new slice containing only the elements that satisfy the predicate

Example:

Where([]int{1, 2, 3, 4}, func(n int) bool { return n % 2 == 0 })
// Returns: []int{2, 4}

Where([]int{1, 3, 5}, func(n int) bool { return n % 2 == 0 })
// Returns: []int{}

func WhereIn

func WhereIn[T any, K comparable](collection []T, keyFunc func(T) K, values []K) []T

WhereIn filters the collection by a given key/value contained within the given array.

Parameters:

  • collection: The slice to filter
  • keyFunc: The function that extracts the key to check against the values
  • values: The slice of values to check against

Returns:

  • []T: A new slice containing only the elements whose extracted keys are in the values slice

Example:

WhereIn([]int{1, 2, 3, 4}, func(n int) int { return n }, []int{2, 4})
// Returns: []int{2, 4}

WhereIn([]int{1, 2, 3, 4, 5}, func(n int) int { return n % 3 }, []int{0, 1})
// Returns: []int{1, 3, 4} (because 1%3=1, 3%3=0, 4%3=1, which are in [0,1])

func WhereNotIn

func WhereNotIn[T any, K comparable](collection []T, keyFunc func(T) K, values []K) []T

WhereNotIn filters the collection by a given key/value not contained within the given array.

Parameters:

  • collection: The slice to filter
  • keyFunc: The function that extracts the key to check against the values
  • values: The slice of values to check against

Returns:

  • []T: A new slice containing only the elements whose extracted keys are not in the values slice

Example:

WhereNotIn([]int{1, 2, 3, 4}, func(n int) int { return n }, []int{2, 4})
// Returns: []int{1, 3}

WhereNotIn([]int{1, 2, 3, 4, 5}, func(n int) int { return n % 3 }, []int{0, 1})
// Returns: []int{2, 5} (because 2%3=2, 5%3=2, which are not in [0,1])

func Zip

func Zip[T any](collection []T, arrays ...[]T) [][]T

Zip merges together the values of the given arrays with the values of the original collection.

Parameters:

  • collection: The base slice to merge with other arrays
  • arrays: Variable number of slices to merge with the collection

Returns:

  • [][]T: A new slice of slices where each inner slice contains elements from the same position across all input slices

Example:

Zip([]int{1, 2, 3}, [][]int{{4, 5, 6}})
// Returns: [][]int{{1, 4}, {2, 5}, {3, 6}}

Zip([]int{1, 2}, [][]int{{3, 4}, {5, 6}})
// Returns: [][]int{{1, 3, 5}, {2, 4, 6}}

Types

This section is empty.

Jump to

Keyboard shortcuts

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