genfuncs
import "github.com/nwillc/genfuncs"
Package genfuncs implements various functions utilizing Go's Generics to help avoid writing boilerplate code, in particular when working with slices. Many of the functions are based on Kotlin's Sequence. This package, though usable, is primarily a proof-of-concept since it is likely Go will provide similar at some point soon.
The code is under the ISC License: https://github.com/nwillc/genfuncs/blob/master/LICENSE.md
Index
- func Associate[T, V any, K comparable](slice []T, keyValueFor KeyValueFor[T, K, V]) map[K]V
- func AssociateWith[K comparable, V any](slice []K, valueFor ValueFor[K, V]) map[K]V
- func Distinct[T comparable](slice []T) []T
- func FlatMap[T, R any](slice []T, function Function[T, []R]) []R
- func Fold[T, R any](slice []T, initial R, biFunction BiFunction[R, T, R]) R
- func GroupBy[T any, K comparable](slice []T, keyFor KeyFor[T, K]) map[K][]T
- func Keys[K comparable, V any](m map[K]V) []K
- func Map[T, R any](slice []T, function Function[T, R]) []R
- func Values[K comparable, V any](m map[K]V) []V
- type BiFunction
- type Comparator
- type Function
- type Heap
- type KeyFor
- type KeyValueFor
- type Ordering
- type Predicate
- type Slice
- func (s Slice[T]) All(predicate Predicate[T]) bool
- func (s Slice[T]) Any(predicate Predicate[T]) bool
- func (s Slice[T]) Contains(element T, comparator Comparator[T]) bool
- func (s Slice[T]) Filter(predicate Predicate[T]) Slice[T]
- func (s Slice[T]) Find(predicate Predicate[T]) (T, bool)
- func (s Slice[T]) FindLast(predicate Predicate[T]) (T, bool)
- func (s Slice[T]) JoinToString(stringer Stringer[T], separator string, prefix string, postfix string) string
- func (s Slice[T]) Sort(comparator Comparator[T])
- func (s Slice[T]) SortBy(comparator Comparator[T]) []T
- func (s Slice[T]) Swap(i, j int)
- type Stringer
- type ValueFor
func Associate
func Associate[T, V any, K comparable](slice []T, keyValueFor KeyValueFor[T, K, V]) map[K]V
Associate returns a map containing key/values created by applying a function to elements of the slice.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
"strings"
)
func main() {
byLastName := func(n string) (string, string) {
parts := strings.Split(n, " ")
return parts[1], n
}
names := []string{"fred flintstone", "barney rubble"}
nameMap := genfuncs.Associate(names, byLastName)
fmt.Println(nameMap["rubble"]) // barney rubble
}
func AssociateWith
func AssociateWith[K comparable, V any](slice []K, valueFor ValueFor[K, V]) map[K]V
AssociateWith returns a Map where keys are elements from the given sequence and values are produced by the valueSelector function applied to each element.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
func main() {
oddEven := func(i int) string {
if i%2 == 0 {
return "EVEN"
}
return "ODD"
}
numbers := []int{1, 2, 3, 4}
odsEvensMap := genfuncs.AssociateWith(numbers, oddEven)
fmt.Println(odsEvensMap[2]) // EVEN
fmt.Println(odsEvensMap[3]) // ODD
}
func Distinct
func Distinct[T comparable](slice []T) []T
Distinct returns a slice containing only distinct elements from the given slice.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
func main() {
values := []int{1, 2, 2, 3, 1, 3}
fmt.Println(genfuncs.Distinct(values)) // [1 2 3]
}
func FlatMap
func FlatMap[T, R any](slice []T, function Function[T, []R]) []R
FlatMap returns a slice of all elements from results of transform function being invoked on each element of original slice, and those resultant slices concatenated.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
"strings"
)
var lexicalOrder = genfuncs.OrderedComparator[string]()
var words genfuncs.Slice[string] = []string{"hello", "world"}
func main() {
slicer := func(s string) []string { return strings.Split(s, "") }
fmt.Println(genfuncs.FlatMap(words.SortBy(lexicalOrder), slicer)) // [h e l l o w o r l d]
}
func Fold
func Fold[T, R any](slice []T, initial R, biFunction BiFunction[R, T, R]) R
Fold accumulates a value starting with initial value and applying operation from left to right to current accumulated value and each element.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
func main() {
numbers := []int{1, 2, 3, 4, 5}
sum := func(a int, b int) int { return a + b }
fmt.Println(genfuncs.Fold(numbers, 0, sum)) // 15
}
func GroupBy
func GroupBy[T any, K comparable](slice []T, keyFor KeyFor[T, K]) map[K][]T
GroupBy groups elements of the slice by the key returned by the given keySelector function applied to each element and returns a map where each group key is associated with a slice of corresponding elements.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
func main() {
oddEven := func(i int) string {
if i%2 == 0 {
return "EVEN"
}
return "ODD"
}
numbers := []int{1, 2, 3, 4}
grouped := genfuncs.GroupBy(numbers, oddEven)
fmt.Println(grouped["ODD"]) // [1 3]
}
func Keys
func Keys[K comparable, V any](m map[K]V) []K
Keys returns a slice of all the keys in the map.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
var wordPositions = map[string]int{"hello": 1, "world": 2}
func main() {
keys := genfuncs.Keys(wordPositions)
fmt.Println(keys) // [hello, world]
}
func Map
func Map[T, R any](slice []T, function Function[T, R]) []R
Map returns a slice containing the results of applying the given transform function to each element in the original slice.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
func main() {
numbers := []int{69, 88, 65, 77, 80, 76, 69}
toString := func(i int) string { return string(rune(i)) }
fmt.Println(genfuncs.Map(numbers, toString)) // [E X A M P L E]
}
func Values
func Values[K comparable, V any](m map[K]V) []V
Values returns a slice of all the values in the map.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
var wordPositions = map[string]int{"hello": 1, "world": 2}
func main() {
values := genfuncs.Values(wordPositions)
fmt.Println(values) // [1, 2]
}
type BiFunction
BiFunction accepts two arguments and produces a result.
type BiFunction[T, U, R any] func(T, U) R
type Comparator
Comparator compares two arguments of the same type and returns LessThan, EqualTo or GreaterThan based relative order.
type Comparator[T any] BiFunction[T, T, Ordering]
func FunctionComparator
func FunctionComparator[T, R any](transform Function[T, R], comparator Comparator[R]) Comparator[T]
FunctionComparator composites an existing Comparator[R] and Function[T,R] into a new Comparator[T].
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
"time"
)
func main() {
var unixTime = func(t time.Time) int64 { return t.Unix() }
var timeComparator = genfuncs.FunctionComparator(unixTime, genfuncs.OrderedComparator[int64]())
now := time.Now()
fmt.Println(timeComparator(now, now.Add(time.Second))) // -1
}
func OrderedComparator
func OrderedComparator[T constraints.Ordered]() Comparator[T]
OrderedComparator will create a Comparator from any type included in the constraints.Ordered constraint.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
var lexicalOrder = genfuncs.OrderedComparator[string]()
func main() {
fmt.Println(lexicalOrder("a", "b")) // -1
fmt.Println(lexicalOrder("a", "a")) // 0
fmt.Println(lexicalOrder("b", "a")) // 1
}
func ReverseComparator
func ReverseComparator[T any](comparator Comparator[T]) Comparator[T]
ReverseComparator reverses a Comparator to facilitate switching sort orderings.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
var lexicalOrder = genfuncs.OrderedComparator[string]()
var reverseLexical = genfuncs.ReverseComparator(lexicalOrder)
func main() {
fmt.Println(lexicalOrder("a", "b")) // -1
fmt.Println(reverseLexical("a", "b")) // 1
}
type Function
Function accepts one argument and produces a result.
type Function[T, R any] func(T) R
type Heap
Heap implements either a min or max ordered heap of any type.
type Heap[T any] struct {
// contains filtered or unexported fields
}
func NewHeap
func NewHeap[T any](comparator Comparator[T]) *Heap[T]
NewHeap return a heap ordered based on the Comparator.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
)
var intCmp = genfuncs.OrderedComparator[int]()
func main() {
heap := genfuncs.NewHeap(intCmp)
heap.PushAll(3, 1, 4, 2)
for heap.Len() > 0 {
fmt.Print(heap.Pop()) // 1234
}
fmt.Println()
}
func (*Heap) Len
func (h *Heap[T]) Len() int
Len returns current length of the heap.
func (*Heap) Pop
func (h *Heap[T]) Pop() T
Pop an item off the heap.
func (*Heap) Push
func (h *Heap[T]) Push(v T)
Push a value onto the heap.
func (*Heap) PushAll
func (h *Heap[T]) PushAll(values ...T)
PushAll the values onto the Heap.
type KeyFor
KeyFor is used for generating keys from types, it accepts any type and returns a comparable key for it.
type KeyFor[T any, K comparable] Function[T, K]
type KeyValueFor
KeyValueFor is used to generate a key and value from a type, it accepts any type, and returns a comparable key and any value.
type KeyValueFor[T any, K comparable, V any] func(T) (K, V)
type Ordering
Ordering is the type returned by a Comparator.
type Ordering int
var (
LessThan Ordering = -1
EqualTo Ordering = 0
GreaterThan Ordering = 1
)
type Predicate
Predicate is used evaluate a value, it accepts any type and returns a bool.
type Predicate[T any] func(T) bool
func IsEqualTo
func IsEqualTo[T comparable](a T) Predicate[T]
IsEqualTo creates a Predicate that tests if its argument is equal to a given value.
func IsGreaterThan
func IsGreaterThan[T constraints.Ordered](a T) Predicate[T]
IsGreaterThan creates a Predicate that tests if its argument is greater than a given value.
func IsLessThan
func IsLessThan[T constraints.Ordered](a T) Predicate[T]
IsLessThan creates a Predicate that tests if its argument is less than a given value.
type Slice
type Slice[T any] []T
func (Slice) All
func (s Slice[T]) All(predicate Predicate[T]) bool
All returns true if all elements of slice match the predicate.
func (Slice) Any
func (s Slice[T]) Any(predicate Predicate[T]) bool
Any returns true if any element of the slice matches the predicate.
func (Slice) Contains
func (s Slice[T]) Contains(element T, comparator Comparator[T]) bool
Contains returns true if element is found in slice.
func (Slice) Filter
func (s Slice[T]) Filter(predicate Predicate[T]) Slice[T]
Filter returns a slice containing only elements matching the given predicate.
func (Slice) Find
func (s Slice[T]) Find(predicate Predicate[T]) (T, bool)
Find returns the first element matching the given predicate and true, or false when no such element was found.
func (Slice) FindLast
func (s Slice[T]) FindLast(predicate Predicate[T]) (T, bool)
FindLast returns the last element matching the given predicate and true, or false when no such element was found.
func (Slice) JoinToString
func (s Slice[T]) JoinToString(stringer Stringer[T], separator string, prefix string, postfix string) string
JoinToString creates a string from all the elements using the stringer on each, separating them using separator, and using the given prefix and postfix.
func (Slice) Sort
func (s Slice[T]) Sort(comparator Comparator[T])
Sort sorts a slice by Comparator order.
func (Slice) SortBy
func (s Slice[T]) SortBy(comparator Comparator[T]) []T
SortBy copies a slice, sorts the copy applying the Comparator and returns it.
func (Slice) Swap
func (s Slice[T]) Swap(i, j int)
Swap two values in the slice.
type Stringer
Stringer is used to create string representations, it accepts any type and returns a string.
type Stringer[T any] func(T) string
func StringerStringer
func StringerStringer[T fmt.Stringer]() Stringer[T]
StringerStringer creates a Stringer for any type that implements fmt.Stringer.
Example
package main
import (
"fmt"
"github.com/nwillc/genfuncs"
"time"
)
func main() {
var epoch time.Time
fmt.Println(epoch.String()) // 0001-01-01 00:00:00 +0000 UTC
stringer := genfuncs.StringerStringer[time.Time]()
fmt.Println(stringer(epoch)) // 0001-01-01 00:00:00 +0000 UTC
}
type ValueFor
ValueFor given a comparable key will return a value for it.
type ValueFor[K comparable, T any] Function[K, T]
Generated by gomarkdoc