Code Monkey home page Code Monkey logo

genfuncs's Introduction

License CI codecov.io Releases

Packages

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.

Examples are found in examples_test.go files or projects like https://github.com/nwillc/gordle

The code is under the ISC License: https://github.com/nwillc/genfuncs/blob/master/LICENSE.md

Index

Variables

var (
    F32NumericOrder        = LessThanOrdered[float32]
    F32ReverseNumericOrder = Reverse(F32NumericOrder)
    INumericOrder          = LessThanOrdered[int]
    IReverseNumericOrder   = Reverse(INumericOrder)
    I64NumericOrder        = LessThanOrdered[int64]
    I64ReverseNumericOrder = Reverse(I64NumericOrder)
    SLexicalOrder          = LessThanOrdered[string]
    SReverseLexicalOrder   = Reverse(SLexicalOrder)

    IsBlank    = IsEqualComparable("")
    IsNotBlank = Not(IsBlank)

    F32IsZero = IsEqualComparable(float32(0.0))
    F64IsZero = IsEqualComparable(0.0)
    IIsZero   = IsEqualComparable(0)
)
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 EqualComparable[C comparable](a, b C) bool

EqualComparable tests equality of two given comparable values.

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

GreaterThanOrdered tests if constraints.Ordered a is greater than b.

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

LessThanOrdered tests if constraints.Ordered a is less than b.

func Max

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

Max returns max value of two constraints.Ordered values,

Example

package main

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

func main() {
	fmt.Println(genfuncs.Max(1, 2))         // 2
	fmt.Println(genfuncs.Max("dog", "cat")) // dog
}

func Min

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

Min returns min value of two constraints.Ordered values,

Example

package main

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

func main() {
	fmt.Println(genfuncs.Min(1, 2))         // 1
	fmt.Println(genfuncs.Min("dog", "cat")) // cat
}

BiFunction accepts two arguments and produces a result.

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

func Reverse

func Reverse[T any](lessThan BiFunction[T, T, bool]) BiFunction[T, T, bool]

Reverse reverses a LessThan to facilitate reverse sort ordering.

func TransformArgs[T1, T2, R any](function Function[T1, T2], biFunction BiFunction[T2, T2, R]) BiFunction[T1, T1, R]

TransformArgs uses the function to the arguments to be passed to the BiFunction.

Example

package main

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

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

Function is a single argument function.

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

func Curried

func Curried[A, B, R any](biFunction BiFunction[A, B, R], a A) Function[B, R]

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

func IsEqualComparable[C comparable](a C) Function[C, bool]

IsEqualComparable creates a Predicate that tests equality with a given comparable value.

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

IsGreaterThanOrdered return a GreaterThanOrdered for a.

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

IsLessThanOrdered returns a LessThanOrdered for a.

func Not

func Not[T any](function Function[T, bool]) Function[T, bool]

Not takes a Function returning a bool and returns a Function that inverts the result.

MapKeyFor is used for generating keys from types, it accepts any type and returns a comparable key for it.

type MapKeyFor[T any, K comparable] func(T) K

MapKeyValueFor is used to generate a key and value from a type, it accepts any type, and returns a comparable key and any value.

type MapKeyValueFor[T any, K comparable, V any] func(T) (K, V)

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

type MapValueFor[K comparable, T any] func(K) T

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

type ToString[T any] func(T) string
func StringerToString[T fmt.Stringer]() ToString[T]

StringerToString creates a ToString 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.StringerToString[time.Time]()
	fmt.Println(stringer(epoch)) // 0001-01-01 00:00:00 +0000 UTC
}

container

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

Index

func Associate[T, V any, K comparable](slice Slice[T], keyValueFor genfuncs.MapKeyValueFor[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/container"
	"strings"
)

func main() {
	byLastName := func(n string) (string, string) {
		parts := strings.Split(n, " ")
		return parts[1], n
	}
	names := []string{"fred flintstone", "barney rubble"}
	nameMap := container.Associate(names, byLastName)
	fmt.Println(nameMap["rubble"]) // barney rubble
}

func AssociateWith[K comparable, V any](slice Slice[K], valueFor genfuncs.MapValueFor[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/container"
)

func main() {
	oddEven := func(i int) string {
		if i%2 == 0 {
			return "EVEN"
		}
		return "ODD"
	}
	numbers := []int{1, 2, 3, 4}
	odsEvensMap := container.AssociateWith(numbers, oddEven)
	fmt.Println(odsEvensMap[2]) // EVEN
	fmt.Println(odsEvensMap[3]) // ODD
}

func Contains[K comparable, V any](m map[K]V, key K) bool

Contains tests if a map contains an entry for a given key.

Example

package main

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

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

func main() {
	fmt.Println(container.Contains(wordPositions, "hello")) // true
	fmt.Println(container.Contains(wordPositions, "no"))    // false
}

func Fold

func Fold[T, R any](slice Slice[T], initial R, biFunction genfuncs.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/container"
)

func main() {
	numbers := []int{1, 2, 3, 4, 5}
	sum := func(a int, b int) int { return a + b }
	fmt.Println(container.Fold(numbers, 0, sum)) // 15
}

func GroupBy

func GroupBy[T any, K comparable](slice Slice[T], keyFor genfuncs.MapKeyFor[T, K]) map[K]Slice[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/container"
)

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

type Bag

Bag is a minimal container that accepts elements.

type Bag[T any] interface {
    // Add an element to the Bag.
    Add(t T)
    // AddAll elements to the Bag.
    AddAll(t ...T)
    // Len returns length of the Bag.
    Len() int
    // Values returns a copy of the current values in the Bag without modifying the contents.
    Values() Slice[T]
}

type Deque

Deque is a doubly ended Queue with default behavior of a Fifo but provides left and right access.

type Deque[T any] struct {
    // contains filtered or unexported fields
}
func NewDeque[T any](t ...T) *Deque[T]

NewDeque creates a Deque containing any provided elements.

func (*Deque) Add

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

Add an element to the right of the Deque.

func (*Deque) AddAll

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

AddAll elements to the right of the Deque.

func (*Deque) AddLeft

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

AddLeft an element to the left of the Deque.

func (*Deque) AddRight

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

AddRight an element to the right of the Deque.

func (*Deque) Cap

func (d *Deque[T]) Cap() int

Cap returns the capacity of the Deque.

func (*Deque) Len

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

Len reports the length of the Deque.

func (*Deque) Peek

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

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

func (*Deque) PeekLeft

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

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

func (*Deque) PeekRight

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

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

func (*Deque) Remove

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

Remove and return the left most element in the Deque.

func (*Deque) RemoveLeft

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

RemoveLeft and return the left most element in the Deque.

func (*Deque) RemoveRight

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

RemoveRight and return the right most element in the Deque.

func (*Deque) Values

func (d *Deque[T]) Values() Slice[T]

Values in the Deque returned in a new Slice.

type Heap

Heap implements either a min or max ordered heap of any type. Heap implements Queue.

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

func NewHeap

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

NewHeap return a heap ordered based on the LessThan and pushes any values provided.

Example

package main

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

func main() {
	heap := container.NewHeap(genfuncs.INumericOrder, 3, 1, 4, 2)
	for heap.Len() > 0 {
		fmt.Print(heap.Remove())
	}
	fmt.Println()
	// 1234
}

func (*Heap) Add

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

Add a value onto the heap.

func (*Heap) AddAll

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

AddAll the values onto the Heap.

func (*Heap) Len

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

Len returns current length of the heap.

func (*Heap) Peek

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

Peek returns the next element without removing it.

func (*Heap) Remove

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

Remove an item off the heap.

func (*Heap) Values

func (h *Heap[T]) Values() Slice[T]

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

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 NewMapSet[T comparable](t ...T) *MapSet[T]

NewMapSet returns a new MapSet containing given values.

func ToSet

func ToSet[T comparable](slice Slice[T]) *MapSet[T]

func (*MapSet) Add

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

Add element to MapSet.

func (*MapSet) AddAll

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

AddAll elements to MapSet.

func (*MapSet) Contains

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

Contains returns true if MapSet contains element.

func (*MapSet) Len

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

Len returns the length of the MapSet.

func (*MapSet) Remove

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

Remove an element from the MapSet.

func (*MapSet) Values

func (h *MapSet[T]) Values() Slice[T]

Values returns the elements in the MapSet as a Slice.

type Queue

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

type Queue[T any] interface {

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

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
    // Values in the Set as a Slice.
    Values() Slice[T]
    // Remove a given element from the Set.
    Remove(t T)
    // contains filtered or unexported methods
}

type Slice

Slice is a generic type corresponding to a standard Go slice.

type Slice[T any] []T
func Distinct[T comparable](slice Slice[T]) Slice[T]

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

Example

package main

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

func main() {
	values := []int{1, 2, 2, 3, 1, 3}
	fmt.Println(container.Distinct(values)) // [1 2 3]
}

func FlatMap

func FlatMap[T, R any](slice Slice[T], function genfuncs.Function[T, Slice[R]]) Slice[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"
	"github.com/nwillc/genfuncs/container"
	"strings"
)

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

func main() {
	slicer := func(s string) container.Slice[string] { return strings.Split(s, "") }
	fmt.Println(container.FlatMap(words.SortBy(genfuncs.SLexicalOrder), slicer)) // [h e l l o w o r l d]
}

func Keys

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

Keys returns a slice of all the keys in the map.

Example

package main

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

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

func main() {
	keys := container.Keys(wordPositions)
	fmt.Println(keys) // [hello, world]
}

func Map

func Map[T, R any](slice Slice[T], function genfuncs.Function[T, R]) Slice[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/container"
)

func main() {
	numbers := []int{69, 88, 65, 77, 80, 76, 69}
	toString := func(i int) string { return string(rune(i)) }
	fmt.Println(container.Map(numbers, toString)) // [E X A M P L E]
}

func Values

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

Values returns a slice of all the values in the map.

Example

package main

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

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

func main() {
	values := container.Values(wordPositions)
	fmt.Println(values) // [1, 2]
}

func (Slice) All

func (s Slice[T]) All(predicate genfuncs.Function[T, bool]) bool

All returns true if all elements of slice match the predicate.

func (Slice) Any

func (s Slice[T]) Any(predicate genfuncs.Function[T, bool]) bool

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

func (Slice) Compare

func (s Slice[T]) Compare(s2 Slice[T], comparison genfuncs.BiFunction[T, T, bool]) bool

Compare one Slice to another, applying a comparison to each pair of corresponding entries. Compare returns true if all the pair's comparison return true. While the comparison might test equality it could have any behavior.

func (Slice) Filter

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

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

func (Slice) Find

func (s Slice[T]) Find(predicate genfuncs.Function[T, bool]) (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 genfuncs.Function[T, bool]) (T, bool)

FindLast returns the last element matching the given predicate and true, or false when no such element was found.

func (Slice) ForEach

func (s Slice[T]) ForEach(fn func(t T))

ForEach element of the Slice 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 (Slice) ForEachI

func (s Slice[T]) ForEachI(fn func(i int, t T))

ForEachI element of the Slice invoke given function with the element and its index in the Slice. Syntactic sugar for a range that intends to traverse all the elements, i.e. no exiting midway through.

func (Slice) JoinToString

func (s Slice[T]) JoinToString(stringer genfuncs.ToString[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) Random

func (s Slice[T]) Random() T

func (Slice) Sort

func (s Slice[T]) Sort(lessThan genfuncs.BiFunction[T, T, bool])

Sort sorts a slice by the LessThan order.

func (Slice) SortBy

func (s Slice[T]) SortBy(lessThan genfuncs.BiFunction[T, T, bool]) Slice[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.

version

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

Index

Constants

Version number for official releases.

const Version = "v0.6.5"

Generated by gomarkdoc

genfuncs's People

Contributors

nwillc avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.