ProductPromotion
Logo

Go.Lang

made by https://0x3d.site

GitHub - nwillc/genfuncs: Go 1.18+ polymorphic generic containers and functions.
Go 1.18+ polymorphic generic containers and functions. - nwillc/genfuncs
Visit Site

GitHub - nwillc/genfuncs: Go 1.18+ polymorphic generic containers and functions.

GitHub - nwillc/genfuncs: Go 1.18+ polymorphic generic containers and functions.

License CI codecov.io goreportcard.com Reference Mentioned in Awesome Go Releases

Genfuncs Package

Genfuncs implements various functions utilizing Go's Generics to help avoid writing boilerplate code, in particular when working with containers like heap, list, map, queue, set, slice, etc. Many of the functions are based on Kotlin's Sequence and Map. Some functional patterns like Result and Promises are presents. Attempts were also made to introduce more polymorphism into Go's containers. This package, while very usable, is primarily a proof-of-concept since it is likely Go will provide similar before long. In fact, golang.org/x/exp/slices and golang.org/x/exp/maps offer some similar functions and I incorporate them here.

Code Style

The coding style is not always idiomatic, in particular:

  • All functions have named return values and those variable are used in the return statements.
  • Some places where the range build-in could have been used instead use explicit indexing.

Both of these, while less idiomatic, were done because they measurably improve performance.

General notes:

  • A Map interface is provided to allow both Go's normal map and it's sync.Map to be used polymorphically.
  • The bias of these functions where appropriate is to be pure, without side effects, at the cost of copying data.
  • Examples are found in *examples_test.go files or projects like gordle, gorelease or gotimer.

License

The code is under the ISC License.

Requirements

Build with Go 1.18+

Getting

go get github.com/nwillc/genfuncs

Packages

genfuncs

import "github.com/nwillc/genfuncs"

Index

Variables

var (
    // Orderings
    LessThan    = -1
    EqualTo     = 0
    GreaterThan = 1

    // Predicates
    IsBlank    = OrderedEqualTo("")
    IsNotBlank = Not(IsBlank)
    F32IsZero  = OrderedEqualTo(float32(0.0))
    F64IsZero  = OrderedEqualTo(0.0)
    IIsZero    = OrderedEqualTo(0)
)
var (
    // PromiseNoActionErrorMsg indicates a Promise was created for no action.
    PromiseNoActionErrorMsg = "promise requested with no action"
    // PromisePanicErrorMsg indicates the action of a Promise caused a panic.
    PromisePanicErrorMsg = "promise action panic"
)
var IllegalArguments = fmt.Errorf("illegal arguments")

NoSuchElement error is used by panics when attempts are made to access out of bounds.

var NoSuchElement = fmt.Errorf("no such element")

func Empty

func Empty[T any]\(\) (empty T)

Empty return an empty value of type T.

func Max

func Max[T constraints.Ordered](v ...T) (max T)

Max returns max value one or more constraints.Ordered values,

package main

import (
	"fmt"

	"github.com/nwillc/genfuncs"
)

func main() {
	fmt.Println(genfuncs.Max(1, 2))
	words := []string{"dog", "cat", "gorilla"}
	fmt.Println(genfuncs.Max(words...))
}

Output

2
gorilla

func Min

func Min[T constraints.Ordered](v ...T) (min T)

Min returns min value of one or more constraints.Ordered values,

package main

import (
	"fmt"

	"github.com/nwillc/genfuncs"
)

func main() {
	fmt.Println(genfuncs.Min(1, 2))
	words := []string{"dog", "cat", "gorilla"}
	fmt.Println(genfuncs.Min(words...))
}

Output

1
cat

func Ordered

func Ordered[T constraints.Ordered](a, b T) (order int)

Ordered performs old school -1/0/1 comparison of constraints.Ordered arguments.

func OrderedEqual

func OrderedEqual[O constraints.Ordered](a, b O) (orderedEqualTo bool)

OrderedEqual returns true jf a is ordered equal to b.

func OrderedGreater

func OrderedGreater[O constraints.Ordered](a, b O) (orderedGreaterThan bool)

OrderedGreater returns true if a is ordered greater than b.

func OrderedLess

func OrderedLess[O constraints.Ordered](a, b O) (orderedLess bool)

OrderedLess returns true if a is ordered less than b.

type BiFunction

BiFunction accepts two arguments and produces a result.

type BiFunction[T, U, R any] func(T, U) R

func TransformArgs

func TransformArgs[T1, T2, R any](transform Function[T1, T2], operation BiFunction[T2, T2, R]) (fn BiFunction[T1, T1, R])

TransformArgs uses the function to transform the arguments to be passed to the operation.

package main

import (
	"fmt"
	"time"

	"github.com/nwillc/genfuncs"
)

func main() {
	var unixTime = func(t time.Time) int64 { return t.Unix() }
	var chronoOrder = genfuncs.TransformArgs(unixTime, genfuncs.OrderedLess[int64])
	now := time.Now()
	fmt.Println(chronoOrder(now, now.Add(time.Second)))
}

Output

true

type Function

Function is a single argument function.

type Function[T, R any] func(T) R

func Curried

func Curried[A, R any](operation BiFunction[A, A, R], a A) (fn Function[A, R])

Curried takes a BiFunction and one argument, and Curries the function to return a single argument Function.

func Not

func Not[T any](predicate Function[T, bool]) (fn Function[T, bool])

Not takes a predicate returning and inverts the result.

func OrderedEqualTo

func OrderedEqualTo[O constraints.Ordered](a O) (fn Function[O, bool])

OrderedEqualTo return a function that returns true if its argument is ordered equal to a.

func OrderedGreaterThan

func OrderedGreaterThan[O constraints.Ordered](a O) (fn Function[O, bool])

OrderedGreaterThan returns a function that returns true if its argument is ordered greater than a.

func OrderedLessThan

func OrderedLessThan[O constraints.Ordered](a O) (fn Function[O, bool])

OrderedLessThan returns a function that returns true if its argument is ordered less than a.

type Promise

Promise provides asynchronous Result of an action.

type Promise[T any] struct {
    // contains filtered or unexported fields
}

func NewPromise

func NewPromise[T any](ctx context.Context, action func(context.Context) *Result[T]) *Promise[T]

NewPromise creates a Promise for an action.

func NewPromiseFromResult

func NewPromiseFromResult[T any](result *Result[T]) *Promise[T]

NewPromiseFromResult returns a completed Promise with the specified result.

func (*Promise[T]) Cancel

func (p *Promise[T]) Cancel()

Cancel the Promise which will allow any action that is listening on `<-ctx.Done()` to complete.

func (*Promise[T]) OnError

func (p *Promise[T]) OnError(action func(error)) *Promise[T]

OnError returns a new Promise with an error handler waiting on the original Promise.

func (*Promise[T]) OnSuccess

func (p *Promise[T]) OnSuccess(action func(t T)) *Promise[T]

OnSuccess returns a new Promise with a success handler waiting on the original Promise.

func (*Promise[T]) Wait

func (p *Promise[T]) Wait() *Result[T]

Wait on the completion of a Promise.

type Result

Result is an implementation of the Maybe pattern. This is mostly for experimentation as it is a poor fit with Go's traditional idiomatic error handling.

type Result[T any] struct {
    // contains filtered or unexported fields
}

func NewError

func NewError[T any](err error) *Result[T]

NewError for an error.

func NewResult

func NewResult[T any](t T) *Result[T]

NewResult for a value.

func NewResultError

func NewResultError[T any](t T, err error) *Result[T]

NewResultError creates a Result from a value, error tuple.

func (*Result[T]) Error

func (r *Result[T]) Error() error

Error of the Result, nil if Ok().

func (*Result[T]) MustGet

func (r *Result[T]) MustGet() T

MustGet returns the value of the Result if Ok() or if not, panics with the error.

func (*Result[T]) Ok

func (r *Result[T]) Ok() bool

Ok returns the status of Result, is it ok, or an error.

func (*Result[T]) OnError

func (r *Result[T]) OnError(action func(e error)) *Result[T]

OnError performs the action if Result is not Ok().

func (*Result[T]) OnSuccess

func (r *Result[T]) OnSuccess(action func(t T)) *Result[T]

OnSuccess performs action if Result is Ok().

func (*Result[T]) OrElse

func (r *Result[T]) OrElse(v T) T

OrElse returns the value of the Result if Ok(), or the value v if not.

func (*Result[T]) OrEmpty

func (r *Result[T]) OrEmpty() T

OrEmpty will return the value of the Result or the empty value if Error.

func (*Result[T]) String

func (r *Result[T]) String() string

String returns a string representation of Result, either the value or error.

func (*Result[T]) Then

func (r *Result[T]) Then(action func(t T) *Result[T]) *Result[T]

Then performs the action on the Result.

type ToString

ToString is used to create string representations, it accepts any type and returns a string.

type ToString[T any] func(T) string

func StringerToString

func StringerToString[T fmt.Stringer]() (fn ToString[T])

StringerToString creates a ToString for any type that implements fmt.Stringer.

package main

import (
	"fmt"
	"time"

	"github.com/nwillc/genfuncs"
)

func main() {
	var epoch time.Time
	fmt.Println(epoch.String())
	stringer := genfuncs.StringerToString[time.Time]()
	fmt.Println(stringer(epoch))
}

Output

0001-01-01 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC

container

import "github.com/nwillc/genfuncs/container"

Index

type Container

Container is a minimal container that HasValues and accepts additional elements.

type Container[T any] interface {

    // Add an element to the Container.
    Add(t T)
    // AddAll elements to the Container.
    AddAll(t ...T)
    // contains filtered or unexported methods
}

type Deque

Deque is a doubly ended implementation of Queue with default behavior of a Fifo but provides left and right access. Employs a List for storage.

type Deque[T any] struct {
    // contains filtered or unexported fields
}

func NewDeque

func NewDeque[T any](t ...T) (degue *Deque[T])

NewDeque creates a Deque containing any provided elements.

func (*Deque[T]) Add

func (d *Deque[T]) Add(t T)

Add an element to the right of the Deque.

func (*Deque[T]) AddAll

func (d *Deque[T]) AddAll(t ...T)

AddAll elements to the right of the Deque.

func (*Deque[T]) AddLeft

func (d *Deque[T]) AddLeft(t T)

AddLeft an element to the left of the Deque.

func (*Deque[T]) AddRight

func (d *Deque[T]) AddRight(t T)

AddRight an element to the right of the Deque.

func (*Deque[T]) Iterator

func (d *Deque[T]) Iterator() Iterator[T]

func (*Deque[T]) Len

func (d *Deque[T]) Len() (length int)

Len reports the length of the Deque.

func (*Deque[T]) Peek

func (d *Deque[T]) Peek() (value T)

Peek returns the left most element in the Deque without removing it.

func (*Deque[T]) PeekLeft

func (d *Deque[T]) PeekLeft() (value T)

PeekLeft returns the left most element in the Deque without removing it.

func (*Deque[T]) PeekRight

func (d *Deque[T]) PeekRight() (value T)

PeekRight returns the right most element in the Deque without removing it.

func (*Deque[T]) Remove

func (d *Deque[T]) Remove() (value T)

Remove and return the left most element in the Deque.

func (*Deque[T]) RemoveLeft

func (d *Deque[T]) RemoveLeft() (value T)

RemoveLeft and return the left most element in the Deque.

func (*Deque[T]) RemoveRight

func (d *Deque[T]) RemoveRight() (value T)

RemoveRight and return the right most element in the Deque.

func (*Deque[T]) Values

func (d *Deque[T]) Values() (values GSlice[T])

Values in the Deque returned in a new GSlice.

type GMap

GMap is a generic type employing the standard Go map and implementation Map.

type GMap[K comparable, V any] map[K]V

func (GMap[K, V]) All

func (m GMap[K, V]) All(predicate genfuncs.Function[V, bool]) (ok bool)

All returns true if all values in GMap satisfy the predicate.

func (GMap[K, V]) Any

func (m GMap[K, V]) Any(predicate genfuncs.Function[V, bool]) (ok bool)

Any returns true if any values in GMap satisfy the predicate.

func (GMap[K, V]) Contains

func (m GMap[K, V]) Contains(key K) (isTrue bool)

Contains returns true if the GMap contains the given key.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs/container"
)

var wordPositions = container.GMap[string, int]{"hello": 1, "world": 2}

func main() {
	fmt.Println(wordPositions.Contains("hello"))
	fmt.Println(wordPositions.Contains("no"))
}

Output

true
false

func (GMap[K, V]) Delete

func (m GMap[K, V]) Delete(key K)

Delete an entry in the GMap.

func (GMap[K, V]) Filter

func (m GMap[K, V]) Filter(predicate genfuncs.Function[V, bool]) (result GMap[K, V])

Filter a GMap by a predicate, returning a new GMap that contains only values that satisfy the predicate.

func (GMap[K, V]) FilterKeys

func (m GMap[K, V]) FilterKeys(predicate genfuncs.Function[K, bool]) (result GMap[K, V])

FilterKeys returns a new GMap that contains only values whose key satisfy the predicate.

func (GMap[K, V]) ForEach

func (m GMap[K, V]) ForEach(action func(k K, v V))

ForEach performs the given action on each entry in the GMap.

func (GMap[K, V]) Get

func (m GMap[K, V]) Get(key K) (v V, ok bool)

Get returns an entry from the Map. The returned bool indicates if the key is in the Map.

func (GMap[K, V]) GetOrElse

func (m GMap[K, V]) GetOrElse(k K, defaultValue func() V) (value V)

GetOrElse returns the value at the given key if it exists or returns the result of defaultValue.

func (GMap[K, V]) Iterator

func (m GMap[K, V]) Iterator() Iterator[V]

Iterator creates an iterator for the values in the GMap.

func (GMap[K, V]) Keys

func (m GMap[K, V]) Keys() (keys GSlice[K])

Keys return a GSlice containing the keys of the GMap.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
)

var wordPositions = container.GMap[string, int]{"hello": 1, "world": 2}

func main() {
	fmt.Println(wordPositions.Keys().SortBy(genfuncs.OrderedLess[string]))
}

Output

[hello world]

func (GMap[K, V]) Len

func (m GMap[K, V]) Len() (length int)

Len is the number of elements in the GMap.

func (GMap[K, V]) Put

func (m GMap[K, V]) Put(key K, value V)

Put a key and value in the Map.

func (GMap[K, V]) Values

func (m GMap[K, V]) Values() (values GSlice[V])

Values returns a GSlice of all the values in the GMap.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs/container"
)

var wordPositions = container.GMap[string, int]{"hello": 1, "world": 2}

func main() {
	wordPositions.Values().ForEach(func(_, i int) { fmt.Println(i) })
}

Output

1
2

type GSlice

GSlice is a generic type corresponding to a standard Go slice that implements HasValues.

type GSlice[T any] []T

func (GSlice[T]) Filter

func (s GSlice[T]) Filter(predicate genfuncs.Function[T, bool]) GSlice[T]

Filter returns a slice containing only elements matching the given predicate.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
)

var isGreaterThanZero = genfuncs.OrderedGreaterThan(0)

func main() {
	var values container.GSlice[int] = []int{1, -2, 2, -3}
	values.Filter(isGreaterThanZero).ForEach(func(_, i int) {
		fmt.Println(i)
	})
}

Output

1
2

func (GSlice[T]) ForEach

func (s GSlice[T]) ForEach(action func(i int, t T))

ForEach element of the GSlice invoke given function with the element. Syntactic sugar for a range that intends to traverse all the elements, i.e. no exiting midway through.

func (GSlice[T]) Iterator

func (s GSlice[T]) Iterator() Iterator[T]

Iterator returns an Iterator that will iterate over the GSlice.

func (GSlice[T]) Len

func (s GSlice[T]) Len() int

Len is the number of elements in the GSlice.

func (GSlice[T]) Random

func (s GSlice[T]) Random() (t T)

Random returns a random element of the GSlice.

func (GSlice[T]) SortBy

func (s GSlice[T]) SortBy(order genfuncs.BiFunction[T, T, bool]) (sorted GSlice[T])

SortBy copies a slice, sorts the copy applying the Ordered and returns it. This is not a pure function, the GSlice is sorted in place, the returned slice is to allow for fluid calls in chains.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
)

func main() {
	var numbers container.GSlice[int] = []int{1, 0, 9, 6, 0}
	fmt.Println(numbers)
	fmt.Println(numbers.SortBy(genfuncs.OrderedLess[int]))
}

Output

[1 0 9 6 0]
[0 0 1 6 9]

func (GSlice[T]) Swap

func (s GSlice[T]) Swap(i, j int)

Swap two values in the slice.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
)

var words container.GSlice[string] = []string{"hello", "world"}

func main() {
	words = words.SortBy(genfuncs.OrderedLess[string])
	words.Swap(0, 1)
	fmt.Println(words)
}

Output

[world hello]

func (GSlice[T]) Values

func (s GSlice[T]) Values() (values GSlice[T])

Values is the GSlice itself.

type HasValues

HasValues is an interface that indicates a struct contains values that can counted and be retrieved.

type HasValues[T any] interface {
    // Len returns length of the Container.
    Len() int
    // Values returns a copy of the current values in the Container without modifying the contents.
    Values() GSlice[T]
}

type Heap

Heap implements an ordered heap of any type which can be min heap or max heap depending on the compare provided. Heap implements Queue.

type Heap[T any] struct {
    // contains filtered or unexported fields
}

func NewHeap

func NewHeap[T any](compare genfuncs.BiFunction[T, T, bool], values ...T) (heap *Heap[T])

NewHeap return a heap ordered based on the compare and adds any values provided.

package main

import (
	"fmt"

	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
)

func main() {
	heap := container.NewHeap[int](genfuncs.OrderedLess[int], 3, 1, 4, 2)
	for heap.Len() > 0 {
		fmt.Print(heap.Remove())
	}
	fmt.Println()
}

Output

1234

func (*Heap[T]) Add

func (h *Heap[T]) Add(v T)

Add a value onto the heap.

func (*Heap[T]) AddAll

func (h *Heap[T]) AddAll(values ...T)

AddAll the values onto the Heap.

func (*Heap[T]) Len

func (h *Heap[T]) Len() (length int)

Len returns current length of the heap.

func (*Heap[T]) Peek

func (h *Heap[T]) Peek() (value T)

Peek returns the next element without removing it.

func (*Heap[T]) Remove

func (h *Heap[T]) Remove() (value T)

Remove an item off the heap.

func (*Heap[T]) Values

func (h *Heap[T]) Values() (values GSlice[T])

Values returns a slice of the values in the Heap in no particular order.

type Iterator

type Iterator[T any] interface {
    HasNext() bool
    Next() T
}

func NewListIterator

func NewListIterator[T any](list *List[T]) Iterator[T]

func NewSliceIterator

func NewSliceIterator[T any](slice []T) Iterator[T]

func NewValuesIterator

func NewValuesIterator[T any](values ...T) Iterator[T]

type List

List is a doubly linked list, inspired by list.List but reworked to be generic. List implements Container.

type List[T any] struct {
    // contains filtered or unexported fields
}

func NewList

func NewList[T any](values ...T) (l *List[T])

NewList instantiates a new List containing any values provided.

func (*List[T]) Add

func (l *List[T]) Add(value T)

Add a value to the right of the List.

func (*List[T]) AddAll

func (l *List[T]) AddAll(values ...T)

AddAll values to the right of the List.

func (*List[T]) AddLeft

func (l *List[T]) AddLeft(value T) (e *ListElement[T])

AddLeft adds a value to the left of the List.

func (*List[T]) AddRight

func (l *List[T]) AddRight(v T) (e *ListElement[T])

AddRight adds a value to the right of the List.

func (*List[T]) ForEach

func (l *List[T]) ForEach(action func(value T))

ForEach invokes the action for each value in the list.

func (*List[T]) Iterator

func (l *List[T]) Iterator() Iterator[T]

Iterator creates an Iterator for the List.

func (*List[T]) Len

func (l *List[T]) Len() (length int)

Len returns the number of values in the List.

func (*List[T]) PeekLeft

func (l *List[T]) PeekLeft() (e *ListElement[T])

PeekLeft returns the leftmost value in the List or nil if empty.

func (*List[T]) PeekRight

func (l *List[T]) PeekRight() (e *ListElement[T])

PeekRight returns the rightmost value in the List or nil if empty.

func (*List[T]) Remove

func (l *List[T]) Remove(e *ListElement[T]) (t T)

Remove removes a given value from the List.

func (*List[T]) SortBy

func (l *List[T]) SortBy(order genfuncs.BiFunction[T, T, bool]) (result *List[T])

SortBy sorts the List by the order of the order function. This is not a pure function, the List is sorted, the List returned is to allow for fluid call chains. List does not provide efficient indexed access so a Bubble sort is employed.

func (*List[T]) Values

func (l *List[T]) Values() (values GSlice[T])

Values returns the values in the list as a GSlice.

type ListElement

ListElement is an element of List.

type ListElement[T any] struct {
    Value T
    // contains filtered or unexported fields
}

func (*ListElement[T]) Next

func (e *ListElement[T]) Next() (next *ListElement[T])

Next returns the next list element or nil.

func (*ListElement[T]) Prev

func (e *ListElement[T]) Prev() (prev *ListElement[T])

Prev returns the previous list element or nil.

func (*ListElement[T]) Swap

func (e *ListElement[T]) Swap(e2 *ListElement[T])

Swap the values of two ListElements.

type Map

Map interface to provide a polymorphic and generic interface to map implementations.

type Map[K comparable, V any] interface {
    Contains(key K) bool
    Delete(key K)
    Get(key K) (value V, ok bool)
    Put(key K, value V)
    ForEach(f func(key K, value V))
    Keys() GSlice[K]
    // contains filtered or unexported methods
}

type MapSet

MapSet is a Set implementation based on a map. MapSet implements Set.

type MapSet[T comparable] struct {
    // contains filtered or unexported fields
}

func (*MapSet[T]) Add

func (h *MapSet[T]) Add(t T)

Add element to MapSet.

func (*MapSet[T]) AddAll

func (h *MapSet[T]) AddAll(t ...T)

AddAll elements to MapSet.

func (*MapSet[T]) Contains

func (h *MapSet[T]) Contains(t T) (ok bool)

Contains returns true if MapSet contains element.

func (*MapSet[T]) Iterator

func (h *MapSet[T]) Iterator() Iterator[T]

Iterator returns an Iterator of the current state of the MapSet. This creates a copy of the data.

func (*MapSet[T]) Len

func (h *MapSet[T]) Len() (length int)

Len returns the length of the MapSet.

func (*MapSet[T]) Remove

func (h *MapSet[T]) Remove(t T)

Remove an element from the MapSet.

func (*MapSet[T]) Values

func (h *MapSet[T]) Values() (values GSlice[T])

Values returns the elements in the MapSet as a GSlice.

type Queue

Queue is a container providing some define order when accessing elements. Queue implements Container.

type Queue[T any] interface {

    // Peek returns the next element without removing it.
    Peek() T
    Remove() T
    // contains filtered or unexported methods
}

type Sequence

type Sequence[T any] interface {
    Iterator() Iterator[T]
}

func NewIteratorSequence

func NewIteratorSequence[T any](iterator Iterator[T]) Sequence[T]

type Set

Set is a Container that contains no duplicate elements.

type Set[T comparable] interface {

    // Contains returns true if the Set contains a given element.
    Contains(t T) bool
    // Remove the element from the Set.
    Remove(T)
    // contains filtered or unexported methods
}

func NewMapSet

func NewMapSet[T comparable](t ...T) (set Set[T])

NewMapSet returns a new Set containing given values.

type SyncMap

SyncMap is a Map implementation employing sync.Map and is therefore GoRoutine safe.

type SyncMap[K any, V any] struct {
    // contains filtered or unexported fields
}

func NewSyncMap

func NewSyncMap[K any, V any]() (syncMap *SyncMap[K, V])

NewSyncMap creates a new SyncMap instance.

func (*SyncMap[K, V]) Contains

func (s *SyncMap[K, V]) Contains(key K) (contains bool)

Contains returns true if the Map contains the given key.

func (*SyncMap[K, V]) Delete

func (s *SyncMap[K, V]) Delete(key K)

Delete an entry from the Map.

func (*SyncMap[K, V]) ForEach

func (s *SyncMap[K, V]) ForEach(f func(key K, value V))

ForEach traverses the Map applying the given function to all entries. The sync.Map's any types are cast to the appropriate types.

func (*SyncMap[K, V]) Get

func (s *SyncMap[K, V]) Get(key K) (value V, ok bool)

Get the value for the key. The sync.Map any type to cast to the appropriate type. The returned ok value will be false if the map is not contained in the Map.

func (*SyncMap[K, V]) GetAndDelete

func (s *SyncMap[K, V]) GetAndDelete(key K) (value V, ok bool)

GetAndDelete returns the value from the SyncMap corresponding to the key, returning it, and deletes it.

func (*SyncMap[K, V]) GetOrPut

func (s *SyncMap[K, V]) GetOrPut(key K, value V) (actual V, ok bool)

GetOrPut returns the existing value for the key if present. Otherwise, it puts and returns the given value. The ok result is true if the value was present, false if put.

func (*SyncMap[K, V]) Iterator

func (s *SyncMap[K, V]) Iterator() Iterator[V]

Iterator returns an iterator over a snapshot of the current values.

func (*SyncMap[K, V]) Keys

func (s *SyncMap[K, V]) Keys() (keys GSlice[K])

Keys returns the keys in the Map by traversing it and casting the sync.Map's any to the appropriate type.

func (*SyncMap[K, V]) Len

func (s *SyncMap[K, V]) Len() (length int)

Len returns the element count. This requires a traversal of the Map.

func (*SyncMap[K, V]) Put

func (s *SyncMap[K, V]) Put(key K, value V)

Put a key value pair into the Map.

func (*SyncMap[K, V]) Values

func (s *SyncMap[K, V]) Values() (values GSlice[V])

Values returns the values in the Map, The sync.Map any values is cast to the Map's type.

promises

import "github.com/nwillc/genfuncs/promises"

Index

Variables

var (
    PromiseAnyNoPromisesErrorMsg = "no any without promises"
    PromiseNoneFulfilled         = "no promises fulfilled"
)

func All

func All[T any](ctx context.Context, promises ...*genfuncs.Promise[T]) *genfuncs.Promise[container.GSlice[T]]

All accepts promises and collects their results, returning a container.GSlice of the results in correlating order, or if *any* genfuncs.Promise fails then All returns its error and immediately returns.

func Any

func Any[T any](ctx context.Context, promises ...*genfuncs.Promise[T]) *genfuncs.Promise[T]

Any returns a Promise that will return the first Promise fulfilled, or an error if none were.

func Map

func Map[A, B any](ctx context.Context, aPromise *genfuncs.Promise[A], then genfuncs.Function[A, *genfuncs.Result[B]]) *genfuncs.Promise[B]

Map will Wait for aPromise and then return a new Promise which then maps its result.

results

import "github.com/nwillc/genfuncs/results"

Index

func Map

func Map[T, R any](t *genfuncs.Result[T], transform genfuncs.Function[T, *genfuncs.Result[R]]) (r *genfuncs.Result[R])

Map one Result type to another employing a transform.

func MapError

func MapError[T, R any](t *genfuncs.Result[T]) (r *genfuncs.Result[R])

MapError Result of one type to another.

gslices

import "github.com/nwillc/genfuncs/container/gslices"

Index

func Distinct

func Distinct[T comparable](slice container.GSlice[T]) (distinct container.GSlice[T])

Distinct returns a slice containing only distinct elements from the given slice.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs/container/gslices"
)

func main() {
	values := []int{1, 2, 2, 3, 1, 3}
	gslices.Distinct(values).ForEach(func(_, i int) {
		fmt.Println(i)
	})
}

Output

1
2
3

func FlatMap

func FlatMap[T, R any](slice container.GSlice[T], transform genfuncs.Function[T, container.GSlice[R]]) (result container.GSlice[R])

FlatMap returns a slice of all elements from results of transform being invoked on each element of original slice, and those resultant slices concatenated.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
	"github.com/nwillc/genfuncs/container/gslices"
	"strings"
)

var words container.GSlice[string] = []string{"hello", "world"}

func main() {
	slicer := func(s string) container.GSlice[string] { return strings.Split(s, "") }
	fmt.Println(gslices.FlatMap(words.SortBy(genfuncs.OrderedLess[string]), slicer))
}

Output

[h e l l o w o r l d]

func GroupBy

func GroupBy[T any, K comparable](slice container.GSlice[T], keyFor maps.KeyFor[T, K]) (result container.GMap[K, container.GSlice[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.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container/gslices"
)

func main() {
	oddEven := func(i int) *genfuncs.Result[string] {
		if i%2 == 0 {
			return genfuncs.NewResult("EVEN")
		}
		return genfuncs.NewResult("ODD")
	}
	numbers := []int{1, 2, 3, 4}
	grouped := gslices.GroupBy(numbers, oddEven)
	fmt.Println(grouped["ODD"])
}

Output

[1 3]

func Map

func Map[T, R any](slice container.GSlice[T], transform genfuncs.Function[T, R]) container.GSlice[R]

Map returns a new container.GSlice containing the results of applying the given transform function to each element in the original slice.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs/container/gslices"
)

func main() {
	numbers := []int{69, 88, 65, 77, 80, 76, 69}
	toString := func(i int) string { return string(rune(i)) }
	fmt.Println(gslices.Map(numbers, toString))
}

Output

[E X A M P L E]

func ToSet

func ToSet[T comparable](slice container.GSlice[T]) (set container.Set[T])

ToSet creates a Set from the elements of the GSlice.

maps

import "github.com/nwillc/genfuncs/container/maps"

Index

func Map

func Map[K comparable, V any, R any](m container.Map[K, V], transform genfuncs.BiFunction[K, V, R]) (result container.GSlice[R])

Map returns a GSlice containing the results of applying the given transform function to each element in the GMap.

func Merge

func Merge[K comparable, V any](mv ...container.Map[K, container.GSlice[V]]) (result container.GMap[K, container.GSlice[V]])

Merge merges maps of container.GSlice's together into a new map appending the container.GSlice's when collisions occur.

type Entry

Entry can be used to hold onto a key/value.

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

func NewEntry

func NewEntry[K comparable, V any](k K, v V) *Entry[K, V]

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] func(T) *genfuncs.Result[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) *genfuncs.Result[*Entry[K, V]]

type ValueFor

ValueFor given a comparable key will return a value for it.

type ValueFor[K comparable, T any] func(K) *genfuncs.Result[T]

sequences

import "github.com/nwillc/genfuncs/container/sequences"

Index

func All

func All[T any](sequence container.Sequence[T], predicate genfuncs.Function[T, bool]) (result bool)

All returns true if all elements in the sequence match the predicate.

func Any

func Any[T any](sequence container.Sequence[T], predicate genfuncs.Function[T, bool]) (result bool)

Any returns true if any element of the sequence matches the predicate.

func Associate

func Associate[T any, K comparable, V any](sequence container.Sequence[T], keyValueFor maps.KeyValueFor[T, K, V]) (result *genfuncs.Result[container.GMap[K, V]])

Associate returns a map containing key/values created by applying a function to each value of the container.Iterator returned by the container.Sequence.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
	"github.com/nwillc/genfuncs/container/maps"
	"github.com/nwillc/genfuncs/container/sequences"
	"strings"
)

func main() {
	byLastName := func(n string) *genfuncs.Result[*maps.Entry[string, string]] {
		parts := strings.Split(n, " ")
		return genfuncs.NewResult(maps.NewEntry(parts[1], n))
	}
	names := sequences.NewSequence[string]("fred flintstone", "barney rubble")
	sequences.Associate(names, byLastName).
		OnSuccess(func(nameMap container.GMap[string, string]) {
			fmt.Println(nameMap["rubble"])
		})

}

Output

barney rubble

func AssociateWith

func AssociateWith[K comparable, V any](sequence container.Sequence[K], valueFor maps.ValueFor[K, V]) (result *genfuncs.Result[container.GMap[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.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs"
	"github.com/nwillc/genfuncs/container"
	"github.com/nwillc/genfuncs/container/sequences"
)

func main() {
	oddEven := func(i int) *genfuncs.Result[string] {
		if i%2 == 0 {
			return genfuncs.NewResult("EVEN")
		}
		return genfuncs.NewResult("ODD")
	}
	numbers := sequences.NewSequence[int](1, 2, 3, 4)
	sequences.AssociateWith[int, string](numbers, oddEven).OnSuccess(func(odsEvensMap container.GMap[int, string]) {
		fmt.Println(odsEvensMap[2])
		fmt.Println(odsEvensMap[3])
	})
}

Output

EVEN
ODD

func Collect

func Collect[T any](s container.Sequence[T], c container.Container[T])

Collect elements from a Sequence into a Container.

func Compare

func Compare[T any](s1, s2 container.Sequence[T], comparator func(t1, t2 T) int) int

Compare two sequences with a comparator returning less/equal/greater (-1/0/1) and return comparison of the two.

func Distinct

func Distinct[T comparable](s container.Sequence[T]) container.Sequence[T]

Distinct collects a sequence into a container.Set and returns it as a Sequence.

func Find

func Find[T any](sequence container.Sequence[T], predicate genfuncs.Function[T, bool]) *genfuncs.Result[T]

Find returns the first element matching the given predicate, or Result error of NoSuchElement if not found.

func FindLast

func FindLast[T any](sequence container.Sequence[T], predicate genfuncs.Function[T, bool]) *genfuncs.Result[T]

FindLast returns the last element matching the given predicate, or Result error of NoSuchElement if not found.

func FlatMap

func FlatMap[T, R any](sequence container.Sequence[T], transform genfuncs.Function[T, container.Sequence[R]]) (result container.Sequence[R])

FlatMap returns a sequence of all elements from results of valueFor being invoked on each element of original sequence, and those resultant slices concatenated.

func Fold

func Fold[T, R any](sequence container.Sequence[T], initial R, operation genfuncs.BiFunction[R, T, R]) (result R)

Fold accumulates a value starting with an initial value and applying operation to each value of the container.Iterator returned by the container.Sequence.

package main

import (
	"fmt"
	"github.com/nwillc/genfuncs/container/sequences"
)

func main() {
	sequence := sequences.NewSequence(1, 2, 3, 4)
	sum := sequences.Fold(sequence, 0, func(prior, value int) int {
		return prior + value
	})
	fmt.Println(sum)
}

Output

10

func ForEach

func ForEach[T any](sequence container.Sequence[T], action func(t T))

ForEach calls action for each element of a Sequence.

func IsSorted

func IsSorted[T any](sequence container.Sequence[T], order genfuncs.BiFunction[T, T, bool]) (ok bool)

IsSorted returns true if the GSlice is sorted by order.

func JoinToString

func JoinToString[T any](sequence container.Sequence[T], stringer genfuncs.ToString[T], separator string, prefix string, postfix string) string

JoinToString creates a string from all the elements of a Sequence using the stringer on each, separating them using separator, and using the given prefix and postfix.

func Map

func Map[T, R any](sequence container.Sequence[T], transform genfuncs.Function[T, R]) container.Sequence[R]

Map elements in a Sequence to a new Sequence having applied the valueFor to them.

func NewSequence

func NewSequence[T any](values ...T) (sequence container.Sequence[T])

NewSequence creates a sequence from the provided values.

version

import "github.com/nwillc/genfuncs/gen/version"

Index

Constants

Version number for official releases.

const Version = "v0.20.0"

tests

import "github.com/nwillc/genfuncs/internal/tests"

Index

Constants

const RunExamples = "RUN_EXAMPLES"

func MaybeRunExamples

func MaybeRunExamples(t *testing.T)

Generated by gomarkdoc

Articles
to learn more about the golang concepts.

Resources
which are currently available to browse on.

mail [email protected] to add your project or resources here 🔥.

FAQ's
to know more about the topic.

mail [email protected] to add your project or resources here 🔥.

Queries
or most google FAQ's about GoLang.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory