gollections

module
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2023 License: MIT

README

Gollections

This is a set of utilities aimed at reducing boilerplate code when using slices, maps and extending functionality by new collection implementations such as ordered map or set.

Supports Go version 1.20.

For example, you want to group some users by their role names converted to lowercase:

var users = []User{
    {name: "Bob", age: 26, roles: []Role{{"Admin"}, {"manager"}}},
    {name: "Alice", age: 35, roles: []Role{{"Manager"}}},
    {name: "Tom", age: 18},
}

You can make clear code, extensive, but without dependencies:

var namesByRole = map[string][]string{}
add := func(role string, u User) {
    namesByRole[role] = append(namesByRole[role], u.Name())
}
for _, u := range users {
    roles := u.Roles()
    if len(roles) == 0 {
        add("", u)
    } else {
        for _, r := range roles {
            add(strings.ToLower(r.Name()), u)
        }
    }
}

assert.Equal(t, namesByRole[""], []string{"Tom"})
assert.Equal(t, namesByRole["manager"], []string{"Bob", "Alice"})
assert.Equal(t, namesByRole["admin"], []string{"Bob"})

Or you can write more compact code using the collections API, like so:

var namesByRole = group.ByMultipleKeys(users, func(u User) []string {
    return convert.AndConvert(u.Roles(), Role.Name, strings.ToLower)
}, User.Name)

assert.Equal(t, namesByRole[""], []string{"Tom"})
assert.Equal(t, namesByRole["manager"], []string{"Bob", "Alice"})
assert.Equal(t, namesByRole["admin"], []string{"Bob"})

Installation

go get -u github.com/m4gshm/gollections

or

go get -u github.com/m4gshm/gollections@HEAD

Main packages

All packages consists of functions placed in the package and subpackages aimed to make short aliases of that functions. For example the function slice.SortByOrdered has aliases sort.By and sort.Of.

slice and map_

Contains utility functions of converting, filtering (searching), reducing, cloning elements of embedded slices and maps. The functions compute result in-place. For delayed computations see loops or collection functions.

even := func(i int) bool { return i%2 == 0 }
result := slice.Reduce(
    slice.Convert(
        slice.Filter(slice.Of(1, 2, 3, 4), even),
        strconv.Itoa,
    ),
    op.Sum[string],
)

assert.Equal(t, "24", result)

More examples here and here.

mutable and immutable collections

Provides implelentations of Vector, Set and Map.

Mutables support content appending, updating and deleting (the ordered map implementation is not supported delete operations).
Immutables are read-only datasets.

Detailed description of implementations below.

predicate and breakable break/predicate

Provides predicate builder api that used for filtering collection elements.

bob, _ := slice.First(users, where.Eq(User.Name, "Bob"))

assert.Equal(t, "Bob", bob.Name())
loop, kv/loop and breakable versions break/loop, break/kv/loop

Low level iteration api based on next function.

type (
    next[T any]      func() (element T, ok bool)
    kvNext[K, V any] func() (key K, value V, ok bool)
)

The function retrieves a next element from a dataset and returns ok==true if successful.
The API in most cases is similar to the slice API but with delayed computation which means that the methods don’t compute a result but only return a loop provider. The loop provider is type with a Next method that returns a next processed element.

even := func(i int) bool { return i%2 == 0 }
loopStream := loop.Convert(loop.Filter(loop.Of(1, 2, 3, 4), even).Next, strconv.Itoa)

assert.Equal(t, []string{"2", "4"}, loop.Slice(loopStream.Next))

Breakable loops additionaly have error returned value.

type (
    next[T any]      func() (element T, ok bool, err error)
    kvNext[K, V any] func() (key K, value V, ok bool, err error)
)

It is used for computations where an error may occur.

iter := loop.Conv(loop.Of("1", "2", "3", "ddd4", "5"), strconv.Atoi)
result, err := loop.Slice(iter.Next)

assert.Equal(t, []int{1, 2, 3}, result)
assert.ErrorContains(t, err, "invalid syntax")

Expressions: use, get, first, last

Aimed to evaluate a value using conditions. May cause to make code shorter by not in all cases.
As example:

user := User{name: "Bob", surname: "Smith"}

fullName := use.If(len(user.surname) == 0, user.name).If(len(user.name) == 0, user.surname).
    ElseGet(func() string { return user.name + " " + user.surname })

assert.Equal(t, "Bob Smith", fullName)

instead of:

fullName := ""
if len(user.surname) == 0 {
    fullName = user.name
} else if len(user.name) == 0 {
    fullName = user.surname
} else {
    fullName = user.name + " " + user.surname
}

assert.Equal(t, "Bob Smith", fullName)

Mutable collections

Supports write operations (append, delete, replace).

  • Vector - the simplest based on built-in slice collection.
_ *mutable.Vector[int]   = vector.Of(1, 2, 3)
_ collection.Vector[int] = &mutable.Vector[int]{}
  • Set - collection of unique items, prevents duplicates.
_ *mutable.Set[int]   = set.Of(1, 2, 3)
_ collection.Set[int] = &mutable.Set[int]{}
_ *mutable.Map[int, string]   = map_.Of(k.V(1, "1"), k.V(2, "2"), k.V(3, "3"))
_ collection.Map[int, string] = mutable.NewMapOf(map[int]string{1: "2", 2: "2", 3: "3"})
  • OrderedSet - collection of unique items, prevents duplicates, provides iteration in order of addition.
_ *ordered.Set[int]   = set.Of(1, 2, 3)
_ collection.Set[int] = &ordered.Set[int]{}
  • OrderedMap - same as the Map, but supports iteration in the order in which elements are added.
_ *ordered.Map[int, string]   = map_.Of(k.V(1, "1"), k.V(2, "2"), k.V(3, "3"))
_ collection.Map[int, string] = ordered.NewMapOf(
    /*order  */ []int{3, 1, 2},
    /*uniques*/ map[int]string{1: "2", 2: "2", 3: "3"},
)
Immutable containers

The same underlying interfaces but for read-only use cases.

Collection functions

There are three groups of operations:

Intermediates should wrap one by one to make a lazy computation chain that can be applied to the latest final operation.

var groupedByLength = group.Of(set.Of(
    "seventh", "seventh", //duplicate
    "first", "second", "third", "fourth",
    "fifth", "sixth", "eighth",
    "ninth", "tenth", "one", "two", "three", "1",
    "second", //duplicate
), func(v string) int { return len(v) },
).FilterKey(
    more.Than(3),
).ConvertValue(
    func(v string) string { return v + "_" },
).Map()

assert.Equal(t, map[int][]string{
    5: {"first_", "third_", "fifth_", "sixth_", "ninth_", "tenth_", "three_"},
    6: {"second_", "fourth_", "eighth_"},
    7: {"seventh_"},
}, groupedByLength)

Directories

Path Synopsis
break
c
Package c provides common types and functions
Package c provides common types and functions
kv
Package kv provides key/value types, functions
Package kv provides key/value types, functions
kv/loop
Package loop provides helpers for loop operation over key/value pairs and iterator implementations
Package loop provides helpers for loop operation over key/value pairs and iterator implementations
kv/loop/group
Package group provides short aliases for functions thath are used to group key/value pairs retrieved by a loop
Package group provides short aliases for functions thath are used to group key/value pairs retrieved by a loop
kv/stream
Package stream provides a stream implementation and helper functions
Package stream provides a stream implementation and helper functions
loop
Package loop provides helpers for loop operation and iterator implementations
Package loop provides helpers for loop operation and iterator implementations
map_/convert
Package convert provides key, value convert adapters
Package convert provides key, value convert adapters
map_/filter
Package filter provides helpers for filtering keys or values of a map
Package filter provides helpers for filtering keys or values of a map
op
Package op provides generic operations that can be used for converting or reducing collections, loops, slices
Package op provides generic operations that can be used for converting or reducing collections, loops, slices
predicate
Package predicate provides breakable predicate builders
Package predicate provides breakable predicate builders
predicate/always
Package always provides constant predicate implementations
Package always provides constant predicate implementations
predicate/eq
Package eq provides predicate builder short aliases
Package eq provides predicate builder short aliases
predicate/exclude
Package exclude provides predicate builders
Package exclude provides predicate builders
predicate/less
Package less provides predicate builders
Package less provides predicate builders
predicate/more
Package more provides predicate builders
Package more provides predicate builders
predicate/not
Package not provides negalive predicate builders like 'not equals to'
Package not provides negalive predicate builders like 'not equals to'
predicate/one
Package one provides predicate builders
Package one provides predicate builders
stream
Package stream provides a stream implementation and helper functions
Package stream provides a stream implementation and helper functions
c
Package c provides common types of containers, utility types and functions
Package c provides common types of containers, utility types and functions
Package collection consists of common operations of c.Iterable based collections
Package collection consists of common operations of c.Iterable based collections
convert
Package convert provides converation helpers for collection implementations
Package convert provides converation helpers for collection implementations
filter
Package filter provides aliases for collections filtering helpers
Package filter provides aliases for collections filtering helpers
group
Package group provides short aliases for functions that are used to group collection elements
Package group provides short aliases for functions that are used to group collection elements
immutable
Package immutable provides immutable collection implementations
Package immutable provides immutable collection implementations
immutable/map_
Package map_ provides immutable.Map constructors
Package map_ provides immutable.Map constructors
immutable/ordered
Package ordered provides immutable ordered collection implementations
Package ordered provides immutable ordered collection implementations
immutable/ordered/map_
Package map_ provides immutale ordered.Map constructors
Package map_ provides immutale ordered.Map constructors
immutable/ordered/set
Package set provides ordered.Set constructors and helpers
Package set provides ordered.Set constructors and helpers
immutable/set
Package set provides unordered immutable.Set constructors and helpers
Package set provides unordered immutable.Set constructors and helpers
immutable/vector
Package vector provides ordered immutable.Vector constructors and helpers
Package vector provides ordered immutable.Vector constructors and helpers
mutable
Package mutable provides implementations of mutable containers.
Package mutable provides implementations of mutable containers.
mutable/map_
Package map_ provides unordered mutable.Map constructors
Package map_ provides unordered mutable.Map constructors
mutable/ordered
Package ordered provides mutable ordered collection implementations
Package ordered provides mutable ordered collection implementations
mutable/ordered/map_
Package map_ provides mutable ordered.Map constructors
Package map_ provides mutable ordered.Map constructors
mutable/ordered/set
Package set provides mutable ordered.Set constructors and helpers
Package set provides mutable ordered.Set constructors and helpers
mutable/set
Package set provides unordered mutable.Set constructors and helpers
Package set provides unordered mutable.Set constructors and helpers
mutable/sync
Package sync provides parametrized Map implementation
Package sync provides parametrized Map implementation
mutable/vector
Package vector provides mutable.Vector constructors and helpers
Package vector provides mutable.Vector constructors and helpers
Package convert provides converting helpers
Package convert provides converting helpers
as
Package as provides as.Is alias
Package as provides as.Is alias
ptr
Package ptr provides value, pointer convert helpers
Package ptr provides value, pointer convert helpers
val
Package val provides pointer to value convert helpers
Package val provides pointer to value convert helpers
expr
first
Package first provides helpers for retrieving a first element of a slice that satisfies a condition
Package first provides helpers for retrieving a first element of a slice that satisfies a condition
get
Package get provides conditional expression builders
Package get provides conditional expression builders
last
Package last provides helpers for retrieving a last element of a slice that satisfies a condition
Package last provides helpers for retrieving a last element of a slice that satisfies a condition
use
Package use provides conditional expression builders
Package use provides conditional expression builders
internal
Package iter provides generic constructors and helpers for iterators
Package iter provides generic constructors and helpers for iterators
k
Package k provides the k.V constructor for building key/value pairs
Package k provides the k.V constructor for building key/value pairs
kv
Package kv provides generic key/value pair constructors and helpers
Package kv provides generic key/value pair constructors and helpers
group
Package group provides short aliases for functions that are used to group collection elements
Package group provides short aliases for functions that are used to group collection elements
iter
Package iter provides generic constructors and helpers for key/value iterators
Package iter provides generic constructors and helpers for key/value iterators
iter/group
Package group provides short aliases for functions that are used to group key/values retieved by an iterator
Package group provides short aliases for functions that are used to group key/values retieved by an iterator
loop
Package loop provides helpers for loop operation over key/value pairs and iterator implementations
Package loop provides helpers for loop operation over key/value pairs and iterator implementations
loop/group
Package group provides short aliases for functions thath are used to group key/value pairs retrieved by a loop
Package group provides short aliases for functions thath are used to group key/value pairs retrieved by a loop
stream
Package stream provides a stream implementation and helper functions
Package stream provides a stream implementation and helper functions
Package loop provides helpers for loop operation and iterator implementations
Package loop provides helpers for loop operation and iterator implementations
conv
Package conv provides loop converation helpers
Package conv provides loop converation helpers
convert
Package convert provides loop converation helpers
Package convert provides loop converation helpers
filter
Package filter provides aliases for loop filtering helpers
Package filter provides aliases for loop filtering helpers
first
Package first provides short aliases for loop functions for retrieving a first element
Package first provides short aliases for loop functions for retrieving a first element
flat
Package flat provides short aliases for loop functions
Package flat provides short aliases for loop functions
group
Package group provides short aliases for functions that are used to group elements retrieved by a loop
Package group provides short aliases for functions that are used to group elements retrieved by a loop
range_
Package range_ provides alias for the slice.Range function
Package range_ provides alias for the slice.Range function
sum
Package sum provides sum.Of alias
Package sum provides sum.Of alias
Package map_ provides map processing helper functions
Package map_ provides map processing helper functions
clone
Package clone provides map clone aliases
Package clone provides map clone aliases
convert
Package convert provides key, value convert adapters
Package convert provides key, value convert adapters
filter
Package filter provides helpers for filtering keys or values of a map
Package filter provides helpers for filtering keys or values of a map
group
Package group provides short aliases for functions that are used to group key/values retieved from a source
Package group provides short aliases for functions that are used to group key/values retieved from a source
resolv
Package resolv provides values resolvers for maps thath builded by iterating over key/values loop, slice or collection
Package resolv provides values resolvers for maps thath builded by iterating over key/values loop, slice or collection
Package notsafe provides unsafe helper functions
Package notsafe provides unsafe helper functions
op
Package op provides generic operations that can be used for converting or reducing collections, loops, slices
Package op provides generic operations that can be used for converting or reducing collections, loops, slices
check
Package check provides common predicate functions
Package check provides common predicate functions
check/not
Package not provides negalive predicates like 'not equals to'
Package not provides negalive predicates like 'not equals to'
delay
Package delay provides functions that return anonymous functions for delayed executions.
Package delay provides functions that return anonymous functions for delayed executions.
delay/replace
Package replace provides builders that specifies on value replacing
Package replace provides builders that specifies on value replacing
delay/string_
Package string_ provides string builders
Package string_ provides string builders
delay/string_/join
Package join provides string builders
Package join provides string builders
delay/string_/wrap
Package wrap provides wrap string builders
Package wrap provides wrap string builders
delay/sum
Package sum provides sum.Of alias
Package sum provides sum.Of alias
string_
Package string_ provides string utils
Package string_ provides string utils
string_/join
Package join provides concatenate string utils
Package join provides concatenate string utils
string_/wrap
Package wrap provides string wrap utils
Package wrap provides string wrap utils
sum
Package sum provides sum.Of alias
Package sum provides sum.Of alias
Package predicate provides predicate builders
Package predicate provides predicate builders
always
Package always provides constant predicate implementations
Package always provides constant predicate implementations
eq
Package eq provides predicate builder short aliases
Package eq provides predicate builder short aliases
exclude
Package exclude provides predicate builders
Package exclude provides predicate builders
less
Package less provides predicate builders
Package less provides predicate builders
match
Package match provides short predicate constructors
Package match provides short predicate constructors
more
Package more provides predicate builders
Package more provides predicate builders
not
Package not provides negalive predicate builders like 'not equals to'
Package not provides negalive predicate builders like 'not equals to'
one
Package one provides predicate builders
Package one provides predicate builders
where
Package where provides short predicate constructors
Package where provides short predicate constructors
Package slice provides generic functions for slice types
Package slice provides generic functions for slice types
clone
Package clone provides slice clone aliases
Package clone provides slice clone aliases
clone/reverse
Package reverse provides shor aliases for cloning slices with the elements in reverse order
Package reverse provides shor aliases for cloning slices with the elements in reverse order
clone/sort
Package sort provides sorting of cloned slice elements
Package sort provides sorting of cloned slice elements
clone/stablesort
Package stablesort provides stable sorting of cloned slice elements
Package stablesort provides stable sorting of cloned slice elements
conv
Package conv provides slice converation helpers
Package conv provides slice converation helpers
convert
Package convert provides slice converation helpers
Package convert provides slice converation helpers
filter
Package filter provides aliases for slice filtering helpers
Package filter provides aliases for slice filtering helpers
first
Package first provides short aliases for slice functions for retrieving a first element
Package first provides short aliases for slice functions for retrieving a first element
flat
Package flat provides short aliases for slice functions
Package flat provides short aliases for slice functions
group
Package group provides short aliases for grouping functions
Package group provides short aliases for grouping functions
iter
Package iter provides implementations of slice based itarators
Package iter provides implementations of slice based itarators
last
Package last provides helpers for retrieving the last element of a slice
Package last provides helpers for retrieving the last element of a slice
range_
Package range_ provides alias for the slice.Range function
Package range_ provides alias for the slice.Range function
reverse
Package reverse provides shor aliases for reversng order of a slice
Package reverse provides shor aliases for reversng order of a slice
sort
Package sort provides sorting in place slice elements
Package sort provides sorting in place slice elements
split
Package split provides utils for splitting slices
Package split provides utils for splitting slices
stablesort
Package stablesort provides stable sorting in place slice elements
Package stablesort provides stable sorting in place slice elements
stream
Package stream provides helper functions for transforming a slice to a stream
Package stream provides helper functions for transforming a slice to a stream
sum
Package sum provides sum.Of alias
Package sum provides sum.Of alias
Package stream provides a stream implementation and helper functions
Package stream provides a stream implementation and helper functions
Package walk provides utilily functions for the interface Walker
Package walk provides utilily functions for the interface Walker
group
Package group provides short aliases for functions that are used to group collection elements
Package group provides short aliases for functions that are used to group collection elements

Jump to

Keyboard shortcuts

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