- Notifications
You must be signed in to change notification settings - Fork8
A comprehensive, reusable and efficient concurrent-safe generics utility functions and data structures library.
License
esimov/gogu
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Gogu is a versatile, comprehensive, reusable and efficient concurrent-safe utility functions and data structures library taking advantage of the Go generics. It was inspired by other well known and established frameworks likelodash orApache Commons and some concepts being more closer to the functional programming paradigms.
Its main purpose is to facilitate the ease of working with common data structures like slices, maps and strings, through the implementation of many utility functions commonly used in the day-by-day jobs, but also integrating some of the most used data structure algorithms.
In what's different this library from other Go libraries exploring Go generics?
- It's concurrent-safe (with the exception of B-tree package)
- Implements a dozens of time related functions like:
before
,after
,delay
,memoize
,debounce
,once
,retry
- Rich utility functions to operate with strings
- Very wide range of supported functions to deal with slice and map operations
- Extensive test coverage
- Implements the most used data structures
- Thourough documentation accompanied with examples
$ go get github.com/esimov/gogu
package mainimport"github.com/esimov/gogu"funcmain() {// main program}
Generic Data Structures
bst
: Binary Search Tree data structure implementation, where each node has at most two child nodes and the key of its internal node is greater than all the keys in the respective node's left subtree and less than the ones in the right subtreebtree
: B-tree data structure implementation which is a self-balancing tree data structure maintaining its values in sorted ordercache
: a basic in-memory key-value storage systemheap
: Binary Heap data structure implementation where each node of the subtree is greather or equal then the parent nodelist
: implements a singly and doubly linked list data structurequeue
: package queue implements a FIFO (First-In-First-Out) data structure in two forms: using as storage system a resizing array and a doubly linked liststack
: package stack implements a LIFO (Last-In-First-Out) data structure where the last element added to the stack is processed firsttrie
: package trie provides a thread safe implementation of the ternary search tree data structure. Tries are used for locating specific keys from within a set or for quick lookup searches within a text like auto-completion or spell checking.
General utility functions
Strings utility functions
Slice utility functions
- Chunk
- SumBy
- Contains
- Difference
- DifferenceBy
- Drop
- DropWhile
- DropRightWhile
- Duplicate
- DuplicateWithIndex
- Every
- Filter
- FindAll
- FindIndex
- FindLastIndex
- FindMax
- FindMaxBy
- FindMaxByKey
- FindMin
- FindMinBy
- FindMinByKey
- Flatten
- ForEach
- ForEachRight
- GroupBy
- IndexOf
- Intersection
- IntersectionBy
- LastIndexOf
- Mean
- Merge
- Nth
- Partition
- PartitionMap
- Pluck
- Range
- RangeRight
- Reduce
- Reject
- Reverse
- Shuffle
- SliceToMap
- Some
- Sum
- SumBy
- ToSlice
- Union
- Unique
- UniqueBy
- Unzip
- Without
- Zip
Map utility functions
Concurrency and time related utility functions
funcAbs
funcAbs[TNumber](xT)T
Abs returns the absolut value of x.
funcAfter
funcAfter[V constraints.Signed](n*V,fnfunc())
After creates a function wrapper that does nothing at first. From the nth call onwards, it starts actually invoking the callback function. Useful for grouping responses, where you need to be sure that all the calls have finished just before proceeding to the actual job.
Example
{sample:= []int{1,2,3,4,5,6}length:=len(sample)-1initVal:=0fn:=func(valint)int {returnval+1}ForEach(sample,func(valint) {now:=time.Now()After(&length,func() {<-time.After(10*time.Millisecond)initVal=fn(initVal)after:=time.Since(now).Milliseconds()fmt.Println(after)})})}
10
funcBefore
funcBefore[S~string,Tany,V constraints.Signed](n*V,c*cache.Cache[S,T],fnfunc()T)T
Before creates a function wrapper that memoizes its return value. From the nth call onwards, the memoized result of the last invocation is returned immediately instead of invoking function again. So the wrapper will invoke function at most n-1 times.
Example
{c:=cache.New[string,int](cache.DefaultExpiration,cache.NoExpiration)varn=3sample:= []int{1,2,3}ForEach(sample,func(valint) {fn:=func()int {<-time.After(10*time.Millisecond)returnn}res:=Before(&n,c,fn)// The trick to test this function is to decrease the n value after each iteration.// We can be sure that the callback function is not served from the cache if n > 0.// In this case the cache item "func" should be empty.ifn>0 {val,_:=c.Get("func")fmt.Println(val)fmt.Println(res)}ifn<=0 {// Here the callback function is served from the cache.val,_:=c.Get("func")fmt.Println(val)fmt.Println(res)}})}
<nil>2<nil>1&{0 0}0
funcCamelCase
funcCamelCase[T~string](strT)T
CamelCase converts a string to camelCase (https://en.wikipedia.org/wiki/CamelCase\).
Example
{fmt.Println(CamelCase("Foo Bar"))fmt.Println(CamelCase("--foo-Bar--"))fmt.Println(CamelCase("__foo-_Bar__"))fmt.Println(CamelCase("__FOO BAR__"))fmt.Println(CamelCase(" FOO BAR "))fmt.Println(CamelCase("&FOO&baR "))fmt.Println(CamelCase("&&foo&&bar__"))}
fooBarfooBarfooBarfooBarfooBarfooBarfooBar
funcCapitalize
funcCapitalize[T~string](strT)T
Capitalize converts the first letter of the string to uppercase and the remaining letters to lowercase.
funcChunk
funcChunk[Tcomparable](slice []T,sizeint) [][]T
Chunk split the slice into groups of slices each having the length of size. In case the source slice cannot be distributed equally, the last slice will contain fewer elements.
Example
{fmt.Println(Chunk([]int{0,1,2,3},2))fmt.Println(Chunk([]int{0,1,2,3,4},2))fmt.Println(Chunk([]int{0,1},1))}
[[0 1] [2 3]][[0 1] [2 3] [4]][[0] [1]]
funcClamp
funcClamp[TNumber](num,min,maxT)T
Clamp returns a range-limited number between min and max.
funcCompare
funcCompare[Tcomparable](a,bT,compCompFn[T])int
Compare compares two values using as comparator the callback function argument.
Example
{res1:=Compare(1,2,func(a,bint)bool {returna<b})fmt.Println(res1)res2:=Compare("a","b",func(a,bstring)bool {returna>b})fmt.Println(res2)}
1-1
funcContains
funcContains[Tcomparable](slice []T,valueT)bool
Contains returns true if the value is present in the collection.
funcDelay
funcDelay(delay time.Duration,fnfunc())*time.Timer
Delay invokes the callback function with a predefined delay.
Example
{ch:=make(chanstruct{})now:=time.Now()varvalueuint32timer:=Delay(20*time.Millisecond,func() {atomic.AddUint32(&value,1)ch<-struct{}{}})r1:=atomic.LoadUint32(&value)fmt.Println(r1)<-chiftimer.Stop() {<-timer.C}r1=atomic.LoadUint32(&value)fmt.Println(r1)after:=time.Since(now).Milliseconds()fmt.Println(after)}
0120
funcDifference
funcDifference[Tcomparable](s1,s2 []T) []T
Difference is similar to Without, but returns the values from the first slice that are not present in the second slice.
funcDifferenceBy
funcDifferenceBy[Tcomparable](s1,s2 []T,fnfunc(T)T) []T
DifferenceBy is like Difference, except that invokes a callback function on each element of the slice, applying the criteria by which the difference is computed.
funcDrop
funcDrop[Tany](slice []T,nint) []T
Drop creates a new slice with n elements dropped from the beginning. If n < 0 the elements will be dropped from the back of the collection.
funcDropWhile
funcDropWhile[Tany](slice []T,fnfunc(T)bool) []T
DropWhile creates a new slice excluding the elements dropped from the beginning. Elements are dropped by applying the condition invoked in the callback function.
Example
{res:=DropWhile([]string{"a","aa","bbb","ccc"},func(elemstring)bool {returnlen(elem)>2})fmt.Println(res)}
[a aa]
funcDropRightWhile
funcDropRightWhile[Tany](slice []T,fnfunc(T)bool) []T
DropRightWhile creates a new slice excluding the elements dropped from the end. Elements are dropped by applying the condition invoked in the callback function.
funcDuplicate
funcDuplicate[Tcomparable](slice []T) []T
Duplicate returns the duplicated values of a collection.
funcDuplicateWithIndex[Tcomparable](slice []T)map[T]int
DuplicateWithIndex puts the duplicated values of a collection into a map as a key value pair, where the key is the collection element and the value is its position.
Example
{input:= []int{-1,-1,0,1,2,3,2,5,1,6}fmt.Println(DuplicateWithIndex(input))}
map[-1:0 1:3 2:4]
funcEqual
funcEqual[Tcomparable](a,bT)bool
Equal checks if two values are equal.
funcEvery
funcEvery[Tany](slice []T,fnfunc(T)bool)bool
Every returns true if all the elements of a slice satisfies the criteria of the callback function.
funcFilter
funcFilter[Tany](slice []T,fnfunc(T)bool) []T
Filter returns all the elements from the collection which satisfies the conditional logic of the callback function.
Example
{input:= []int{1,2,3,4,5,10,20,30,40,50}res:=Filter(input,func(valint)bool {returnval>=10})fmt.Println(res)}
[10 20 30 40 50]
funcFilter2DMapCollection[Kcomparable,Vany](collection []map[K]map[K]V,fnfunc(map[K]V)bool) []map[K]map[K]V
Filter2DMapCollection filter out a two-dimensional collection of map items by applying the conditional logic of the callback function.
funcFilterMap
funcFilterMap[Kcomparable,Vany](mmap[K]V,fnfunc(V)bool)map[K]V
FilterMap iterates over the elements of a collection and returns a new collection representing all the items which satisfies the criteria formulated in the callback function.
Example
{input:=map[int]string{1:"John",2:"Doe",3:"Fred"}res:=FilterMap(input,func(vstring)bool {returnv=="John"})fmt.Println(res)}
map[1:John]
funcFilterMapCollection[Kcomparable,Vany](collection []map[K]V,fnfunc(V)bool) []map[K]V
FilterMapCollection filter out a one dimensional collection of map items by applying the conditional logic of the callback function.
Example
{input:= []map[string]int{{"bernie":22},{"robert":30},}res:=FilterMapCollection(input,func(valint)bool {returnval>22})fmt.Println(res)}
[map[robert:30]]
funcFind
funcFind[K constraints.Ordered,Vany](mmap[K]V,fnfunc(V)bool)map[K]V
Find iterates over the elements of a map and returns the first item for which the callback function returns true.
funcFindAll
funcFindAll[Tany](s []T,fnfunc(T)bool)map[int]T
FindAll is like FindIndex, but returns into a map all the values which satisfies the conditional logic of the callback function. The map key represents the position of the found value and the value is the item itself.
Example
{input:= []int{1,2,3,4,2,-2,-1,2}items:=FindAll(input,func(vint)bool {returnv==2})fmt.Println(items)}
map[1:2 4:2 7:2]
funcFindByKey
funcFindByKey[Kcomparable,Vany](mmap[K]V,fnfunc(K)bool)map[K]V
FindByKey is like Find, but returns the first item for which the callback function returns true.
funcFindIndex
funcFindIndex[Tany](s []T,fnfunc(T)bool)int
FindIndex returns the index of the first found element.
funcFindKey
funcFindKey[Kcomparable,Vany](mmap[K]V,fnfunc(V)bool)K
FindKey is like Find, but returns the first item key position for which the callback function returns true.
funcFindLastIndex
funcFindLastIndex[Tany](s []T,fnfunc(T)bool)int
FindLastIndex is like FindIndex, only that returns the index of last found element.
funcFindMax
funcFindMax[T constraints.Ordered](s []T)T
FindMax finds the maximum value of a slice.
funcFindMaxBy
funcFindMaxBy[T constraints.Ordered](s []T,fnfunc(valT)T)T
FindMaxBy is like FindMax except that it accept a callback function and the conditional logic is applied over the resulted value. If there are more than one identical values resulted from the callback function the first one is returned.
funcFindMaxByKey
funcFindMaxByKey[Kcomparable,T constraints.Ordered](mapSlice []map[K]T,keyK) (T,error)
FindMaxByKey finds the maximum value from a map by using some existing key as a parameter.
funcFindMin
funcFindMin[T constraints.Ordered](s []T)T
FindMin finds the minimum value of a slice.
funcFindMinBy
funcFindMinBy[T constraints.Ordered](s []T,fnfunc(valT)T)T
FindMinBy is like FindMin except that it accept a callback function and the conditional logic is applied over the resulted value. If there are more than one identical values resulted from the callback function the first one is used.
funcFindMinByKey
funcFindMinByKey[Kcomparable,T constraints.Ordered](mapSlice []map[K]T,keyK) (T,error)
FindMinByKey finds the minimum value from a map by using some existing key as a parameter.
funcFlatten
funcFlatten[Tany](sliceany) ([]T,error)
Flatten flattens the slice all the way down to the deepest nesting level.
Example
{input:= []any{[]int{1,2,3}, []any{[]int{4},5}}result,_:=Flatten[int](input)fmt.Println(result)}
[1 2 3 4 5]
funcFlip
funcFlip[Tany](fnfunc(args...T) []T)func(args...T) []T
Flip creates a function that invokes fn with arguments reversed.
Example
{flipped:=Flip(func(args...int) []int {returnToSlice(args...)})fmt.Println(flipped(1,2,3))}
[3 2 1]
funcForEach
funcForEach[Tany](slice []T,fnfunc(T))
ForEach iterates over the elements of a collection and invokes the callback fn function on each element.
Example
{input:= []int{1,2,3,4}output:= []int{}ForEach(input,func(valint) {val=val*2output=append(output,val)})fmt.Println(output)}
[2 4 6 8]
funcForEachRight
funcForEachRight[Tany](slice []T,fnfunc(T))
ForEachRight is the same as ForEach, but starts the iteration from the last element.
funcGroupBy
funcGroupBy[T1,T2comparable](slice []T1,fnfunc(T1)T2)map[T2][]T1
GroupBy splits a collection into a key-value set, grouped by the result of running each value through the callback function fn. The return value is a map where the key is the conditional logic of the callback function and the values are the callback function returned values.
Example
{input:= []float64{1.3,1.5,2.1,2.9}res:=GroupBy(input,func(valfloat64)float64 {returnmath.Floor(val)})fmt.Println(res)}
map[1:[1.3 1.5] 2:[2.1 2.9]]
funcInRange
funcInRange[TNumber](num,lo,upT)bool
InRange checks if a number is inside a range.
funcIndexOf
funcIndexOf[Tcomparable](s []T,valT)int
IndexOf returns the index of the firs occurrence of a value in the slice, or -1 if value is not present in the slice.
funcIntersection
funcIntersection[Tcomparable](params...[]T) []T
Intersection computes the list of values that are the intersection of all the slices. Each value in the result should be present in each of the provided slices.
Example
{res1:=Intersection([]int{1,2,4}, []int{0,2,1}, []int{2,1,-2})fmt.Println(res1)res2:=Intersection([]string{"a","b"}, []string{"a","a","a"}, []string{"b","a","e"})fmt.Println(res2)}
[1 2][a]
funcIntersectionBy
funcIntersectionBy[Tcomparable](fnfunc(T)T,params...[]T) []T
IntersectionBy is like Intersection, except that it accepts and callback function which is invoked on each element of the collection.
Example
{result1:=IntersectionBy(func(vfloat64)float64 {returnmath.Floor(v)}, []float64{2.1,1.2}, []float64{2.3,3.4}, []float64{1.0,2.3})fmt.Println(result1)result2:=IntersectionBy(func(vint)int {returnv%2}, []int{1,2}, []int{2,1})fmt.Println(result2)}
[2.1][1 2]
funcInvert
funcInvert[K,Vcomparable](mmap[K]V)map[V]K
Invert returns a copy of the map where the keys become the values and the values the keys. For this to work, all of your map's values should be unique.
funcKebabCase
funcKebabCase[T~string](strT)T
KebabCase converts a string to kebab-case (https://en.wikipedia.org/wiki/Letter_case#Kebab_case\).
Example
{fmt.Println(KebabCase("fooBarBaz"))fmt.Println(KebabCase("Foo BarBaz"))fmt.Println(KebabCase("Foo_Bar_Baz"))}
foo-bar-bazfoo-bar-bazfoo-bar-baz
funcKeys[Kcomparable,Vany](mmap[K]V) []K
Keys retrieve all the existing keys of a map.
funcLastIndexOf
funcLastIndexOf[Tcomparable](s []T,valT)int
LastIndexOf returns the index of the last occurrence of a value.
funcLess
funcLess[T constraints.Ordered](a,bT)bool
Less checks if the first value is less than the second.
funcMap
funcMap[T1,T2any](slice []T1,fnfunc(T1)T2) []T2
Map produces a new slice of values by mapping each value in the list through a transformation function.
funcMapCollection
funcMapCollection[Kcomparable,Vany](mmap[K]V,fnfunc(V)V) []V
MapCollection is like the Map method, but applied to maps. It runs each element of the map over an iteratee function and saves the resulted values into a new map.
funcMapContains
funcMapContains[K,Vcomparable](mmap[K]V,valueV)bool
MapContains returns true if the value is present in the list otherwise false.
funcMapEvery
funcMapEvery[Kcomparable,Vany](mmap[K]V,fnfunc(V)bool)bool
MapEvery returns true if all the elements of a map satisfies the criteria of the callback function.
funcMapKeys
funcMapKeys[Kcomparable,Vany,Rcomparable](mmap[K]V,fnfunc(K,V)R)map[R]V
MapKeys is the opposite of MapValues. It creates a new map with the same number of elements as the original one, but this time the callback function (fn) is invoked over the map keys.
funcMapSome
funcMapSome[Kcomparable,Vany](mmap[K]V,fnfunc(V)bool)bool
MapSome returns true if some elements of a map satisfies the criteria of the callback function.
funcMapUnique
funcMapUnique[K,Vcomparable](mmap[K]V)map[K]V
MapUnique removes the duplicate values from a map.
funcMapValues
funcMapValues[Kcomparable,V,Rany](mmap[K]V,fnfunc(V)R)map[K]R
MapValues creates a new map with the same number of elements as the original one, but running each map value through a callback function (fn).
funcMax
funcMax[T constraints.Ordered](values...T)T
Max returns the biggest value from the provided parameters.
funcMean
funcMean[TNumber](slice []T)T
Mean computes the mean value of the slice elements.
funcMerge
funcMerge[Tany](s []T,params...[]T) []T
Merge merges the first slice with the other slices defined as variadic parameter.
funcMin
funcMin[T constraints.Ordered](values...T)T
Min returns the lowest value from the provided parameters.
funcN
funcN[TNumber](sstring) (T,error)
N converts a string to a generic number.
funcNewDebounce
funcNewDebounce(wait time.Duration) (func(ffunc()),func())
NewDebounce creates a new debounced version of the invoked function which postpone the execution with a time delay passed in as a function argument. It returns a callback function which will be invoked after the predefined delay and also a cancel method which should be invoked to cancel a scheduled debounce.
Example
{var (counter1uint64counter2uint64)f1:=func() {atomic.AddUint64(&counter1,1)}f2:=func() {atomic.AddUint64(&counter2,1)}debounce,cancel:=NewDebounce(10*time.Millisecond)fori:=0;i<2;i++ {forj:=0;j<100;j++ {debounce(f1)}<-time.After(20*time.Millisecond)}cancel()debounce,cancel=NewDebounce(10*time.Millisecond)fori:=0;i<5;i++ {forj:=0;j<50;j++ {debounce(f2)}forj:=0;j<50;j++ {debounce(f2)}<-time.After(20*time.Millisecond)}cancel()c1:=atomic.LoadUint64(&counter1)c2:=atomic.LoadUint64(&counter2)fmt.Println(c1)fmt.Println(c2)}
25
funcNth
funcNth[Tany](slice []T,nthint) (T,error)
Nth returns the nth element of the collection. In case of negative value the nth element is returned from the end of the collection. In case nth is out of bounds an error is returned.
funcNull
funcNull[Tany]()T
funcNumToString
funcNumToString[TNumber](nT)string
NumToString converts a number to a string. In case of a number of type float (float32|float64) this will be rounded to 2 decimal places.
funcOmit
funcOmit[Kcomparable,Vany](collectionmap[K]V,keys...K)map[K]V
Omit is the opposite of Pick, it extracts all the map elements which keys are not omitted.
Example
{res:=Omit(map[string]any{"name":"moe","age":40,"active":false},"name","age")fmt.Println(res)}
map[active:false]
funcOmitBy
funcOmitBy[Kcomparable,Vany](collectionmap[K]V,fnfunc(keyK,valV)bool)map[K]V
OmitBy is the opposite of PickBy, it removes all the map elements for which the callback function returns true.
Example
{res:=OmitBy(map[string]int{"a":1,"b":2,"c":3},func(keystring,valint)bool {returnval%2==1})fmt.Println(res)}
map[b:2]
funcOnce
funcOnce[S~string,Tcomparable,V constraints.Signed](c*cache.Cache[S,T],fnfunc()T)T
Once is like Before, but it's invoked only once. Repeated calls to the modified function will have no effect and the function invocation is returned from the cache.
Example
{c:=cache.New[string,int](cache.DefaultExpiration,cache.NoExpiration)ForEach([]int{1,2,3,4,5},func(valint) {fn:=func(valint)func()int {<-time.After(10*time.Millisecond)returnfunc()int {returnval}}res:=Once[string,int,int](c,fn(val))// We can test the implementation correctness by invoking the `Once` function multiple times.// When it's invoked for the first time the result should be served from the callback function.// From the second invocation onward the results are served from the cache.// In our example the results of each invokation should be always equal with 1.fmt.Println(res)})c.Flush()}
11111
funcPad
funcPad[T~string](strT,sizeint,tokenstring)T
Pad pads string on the left and right sides if it's shorter than length. Padding characters are truncated if they can't be evenly divided by length.
Example
{fmt.Println(Pad("abc",2,"."))fmt.Println(Pad("abc",3,"."))fmt.Println(Pad("abc",4,"."))fmt.Println(Pad("abc",5,"."))}
abcabcabc..abc.
funcPadLeft
funcPadLeft[T~string](strT,sizeint,tokenstring)T
PadLeft pads string on the left side if it's shorter than length. Padding characters are truncated if they exceed length.
Example
{fmt.Println(PadLeft("abc",8,"..."))fmt.Println(PadLeft("abc",4,"_"))fmt.Println(PadLeft("abc",6,"_-"))}
.....abc_abc_-_abc
funcPadRight
funcPadRight[T~string](strT,sizeint,tokenstring)T
PadRight pads string on the right side if it's shorter than length. Padding characters are truncated if they exceed length.
Example
{fmt.Println(PadRight("abc",8,"..."))fmt.Println(PadRight("abc",6,"........"))}
abc.....abc...
funcPartition
funcPartition[Tcomparable](slice []T,fnfunc(T)bool) [2][]T
Partition splits the collection elements into two, the ones which satisfies the condition expressed in the callback function (fn
) and those which does not satisfy the condition.
Example
{input:= []int{0,1,2,3,4,5,6,7,8,9}res1:=Partition(input,func(valint)bool {returnval>=5})fmt.Println(res1)res2:=Partition(input,func(valint)bool {returnval<5})fmt.Println(res2)}
[[5 6 7 8 9] [0 1 2 3 4]][[0 1 2 3 4] [5 6 7 8 9]]
funcPartitionMap
funcPartitionMap[Kcomparable,Vany](mapSlice []map[K]V,fnfunc(map[K]V)bool) [2][]map[K]V
PartitionMap split the collection into two arrays, the one whose elements satisfy the condition expressed in the callback function (fn
) and one whose elements don't satisfy the condition.
funcPick
funcPick[Kcomparable,Vany](collectionmap[K]V,keys...K) (map[K]V,error)
Pick extracts the elements from the map which have the key defined in the allowed keys.
Example
{res,_:=Pick(map[string]any{"name":"moe","age":20,"active":true},"name","age")fmt.Println(res)}
map[age:20 name:moe]
funcPickBy
funcPickBy[Kcomparable,Vany](collectionmap[K]V,fnfunc(keyK,valV)bool)map[K]V
PickBy extracts all the map elements for which the callback function returns truthy.
Example
{res:=PickBy(map[string]int{"aa":1,"b":2,"c":3},func(keystring,valint)bool {returnlen(key)==1})fmt.Println(res)}
map[b:2 c:3]
funcPluck
funcPluck[Kcomparable,Vany](mapSlice []map[K]V,keyK) []V
Pluck extracts all the values of a map by the key definition.
Example
{input:= []map[string]string{{"name":"moe","email":"moe@example.com"},{"name":"larry","email":"larry@example.com"},{"name":"curly","email":"curly@example.com"},{"name":"moly","email":"moly@example.com"},}res:=Pluck(input,"name")fmt.Println(res)}
[moe larry curly moly]
funcRange
funcRange[TNumber](args...T) ([]T,error)
Range creates a slice of integers progressing from start up to, but not including end. This method can accept 1, 2 or 3 arguments. Depending on the number of provided parameters, `start`, `step` and `end` has the following meaning:
[start=0]: The start of the range. If omitted it defaults to 0.
[step=1]: The value to increment or decrement by.
end: The end of the range.
In case you'd like negative values, use a negative step.
Example
{r1,_:=Range(5)r2,_:=Range(1,5)r3,_:=Range(0,2,10)r4,_:=Range(-4)r5,_:=Range(-1,-4)r6,_:=Range(0,-1,-4)r7,_:=Range[float64](0,0.12,0.9)fmt.Println(r1)fmt.Println(r2)fmt.Println(r3)fmt.Println(r4)fmt.Println(r5)fmt.Println(r6)fmt.Println(r7)}
[0 1 2 3 4][1 2 3 4][0 2 4 6 8][0 -1 -2 -3][-1 -2 -3][0 -1 -2 -3][0 0.12 0.24 0.36 0.48 0.6 0.72 0.84]
funcRangeRight
funcRangeRight[TNumber](params...T) ([]T,error)
RangeRight is like Range, only that it populates the slice in descending order.
funcReduce
funcReduce[T1,T2any](slice []T1,fnfunc(T1,T2)T2,initValT2)T2
Reduce reduces the collection to a value which is the accumulated result of running each element in the collection through the callback function yielding a single value.
Example
{input1:= []int{1,2,3,4}res1:=Reduce(input1,func(a,bint)int {returna+b},0)fmt.Println(res1)input2:= []string{"a","b","c","d"}res2:=Reduce(input2,func(a,bstring)string {returnb+a},"")fmt.Println(res2)}
10abcd
funcReject
funcReject[Tany](slice []T,fnfunc(valT)bool) []T
Reject is the opposite of Filter. It returns the values from the collection without the elements for which the callback function returns true.
Example
{input:= []int{1,2,3,4,5,6,10,20,30,40,50}res=Reject(input,func(valint)bool {returnval>=10})fmt.Println(res)}
[1 2 3 4 5 6]
funcReverse
funcReverse[Tany](sl []T) []T
Reverse reverses the order of elements, so that the first element becomes the last, the second element becomes the second to last, and so on.
funcReverseStr
funcReverseStr[T~string](strT)T
ReverseStr returns a new string with the characters in reverse order.
funcShuffle
funcShuffle[Tany](src []T) []T
Shuffle implements the Fisher-Yates shuffle algorithm applied to a slice.
funcSliceToMap
funcSliceToMap[Kcomparable,Tany](s1 []K,s2 []T)map[K]T
SliceToMap converts a slice to a map. It panics in case the parameter slices length are not identical. The map keys will be the items from the first slice and the values the items from the second slice.
funcSnakeCase
funcSnakeCase[T~string](strT)T
SnakeCase converts a string to snake_case (https://en.wikipedia.org/wiki/Snake_case\).
Example
{fmt.Println(SnakeCase("fooBarBaz"))fmt.Println(SnakeCase("Foo BarBaz"))fmt.Println(SnakeCase("Foo_Bar_Baz"))}
foo_bar_bazfoo_bar_bazfoo_bar_baz
funcSome
funcSome[Tany](slice []T,fnfunc(T)bool)bool
Some returns true if some elements of a slice satisfies the criteria of the callback function.
funcSplitAtIndex
funcSplitAtIndex[T~string](strT,indexint) []T
SplitAtIndex split the string at the specified index and returns a slice with the resulted two substrings.
Example
{fmt.Println(SplitAtIndex("abcdef",-1))fmt.Println(SplitAtIndex("abcdef",0))fmt.Println(SplitAtIndex("abcdef",1))fmt.Println(SplitAtIndex("abcdef",2))fmt.Println(SplitAtIndex("abcdef",5))fmt.Println(SplitAtIndex("abcdef",6))}
[ abcdef][a bcdef][ab cdef][abc def][abcdef ][abcdef ]
funcSubstr
funcSubstr[T~string](strT,offset,lengthint)T
Substr returns the portion of string specified by the offset and length.
If offset is non-negative, the returned string will start at the offset'th position in string, counting from zero.
If offset is negative, the returned string will start at the offset'th character from the end of string.
If string is less than offset characters long, an empty string will be returned.
If length is negative, then that many characters will be omitted from the end of string starting from the offset position.
Example
{str1:=Substr("abcdef",0,0)str2:=Substr("abcdef",-1,0)str3:=Substr("abcdef",7,7)str4:=Substr("abcdef",0,20)str5:=Substr("abcdef",5,10)str6:=Substr("abcdef",0,-1)str7:=Substr("abcdef",2,-1)str8:=Substr("abcdef",4,-4)str9:=Substr("abcdef",-3,-1)str10:=Substr("abcdef",1,3)fmt.Println(str1)fmt.Println(str2)fmt.Println(str3)fmt.Println(str4)fmt.Println(str5)fmt.Println(str6)fmt.Println(str7)fmt.Println(str8)fmt.Println(str9)fmt.Println(str10)}
abcdeffabcdecdedebcd
funcSum
funcSum[TNumber](slice []T)T
Sum returns the sum of the slice items. These have to satisfy the type constraints declared as Number.
funcSumBy
funcSumBy[T1any,T2Number](slice []T1,fnfunc(T1)T2)T2
SumBy is like Sum except it accept a callback function which is invoked for each element in the slice to generate the value to be summed.
funcToLower
funcToLower[T~string](strT)T
ToLower converts a string to Lowercase.
funcToSlice
funcToSlice[Tany](args...T) []T
ToSlice returns the function arguments as a slice.
funcToUpper
funcToUpper[T~string](strT)T
ToUpper converts a string to Uppercase.
funcUnion[Tcomparable](sliceany) ([]T,error)
Union computes the union of the passed\-in slice and returns an ordered list of unique items that are present in one or more of the slices.
Example
{input:= []any{[]any{1,2, []any{3, []int{4,5,6}}},7, []int{1,2},3, []int{4,7},8,9,9}res,_:=Union[int](input)fmt.Println(res)}
[1 2 3 4 5 6 7 8 9]
funcUnique
funcUnique[Tcomparable](slice []T) []T
Unique returns the collection unique values.
funcUniqueBy
funcUniqueBy[Tcomparable](slice []T,fnfunc(T)T) []T
UniqueBy is like Unique except that it accept a callback function which is invoked on each element of the slice applying the criteria by which the uniqueness is computed.
funcUnwrap
funcUnwrap[T~string](strT,tokenstring)T
Unwrap a string with the specified token.
Example
{fmt.Println(Unwrap("'abc'","'"))fmt.Println(Unwrap("*abc*","*"))fmt.Println(Unwrap("*a*bc*","*"))fmt.Println(Unwrap("''abc''","''"))fmt.Println(Unwrap("\"abc\"","\""))}
abcabca*bcabcabc
funcUnzip
funcUnzip[Tany](slices...[]T) [][]T
Unzip is the opposite of Zip: given a slice of slices it returns a series of new slices, the first of which contains all the first elements in the input slices, the second of which contains all the second elements, and so on.
funcValues
funcValues[Kcomparable,Vany](mmap[K]V) []V
Values retrieve all the existing values of a map.
funcWithout
funcWithout[T1comparable,T2any](slice []T1,values...T1) []T1
Without returns a copy of the slice with all the values defined in the variadic parameter removed.
Example
{fmt.Println(Without[int,int]([]int{2,1,2,3},1,2))fmt.Println(Without[int,int]([]int{1,2,3,4},3,4))fmt.Println(Without[int,int]([]int{0,1,2,3,4,5},0,3,4,5))fmt.Println(Without[float64,float64]([]float64{1.0,2.2,3.0,4.2},3.0,4.2))}
[3][1 2][1 2][1 2.2]
funcWrap
funcWrap[T~string](strT,tokenstring)T
Wrap a string with the specified token.
Example
{fmt.Println(Unwrap("'abc'","'"))fmt.Println(Unwrap("*abc*","*"))fmt.Println(Unwrap("*a*bc*","*"))fmt.Println(Unwrap("''abc''","''"))fmt.Println(Unwrap("\"abc\"","\""))}
abcabca*bcabcabc
funcWrapAllRune
funcWrapAllRune[T~string](strT,tokenstring)T
WrapAllRune is like Wrap, only that it's applied over runes instead of strings.
Example
{fmt.Println(WrapAllRune("abc",""))fmt.Println(WrapAllRune("abc","'"))fmt.Println(WrapAllRune("abc","*"))fmt.Println(WrapAllRune("abc","-"))}
abc'a''b''c'*a**b**c*-a--b--c-
funcZip
funcZip[Tany](slices...[]T) [][]T
Zip iteratively merges together the values of the slice parameters with the values at the corresponding position.
typeBound
typeBound[T constraints.Signed]struct {Min,MaxT}
func (Bound[T])Enclose
func (bBound[T])Enclose(nthT)bool
Enclose checks if an element is inside the bounds.
typeCompFn
CompFn is a generic function type for comparing two values.
typeCompFn[Tany]func(a,bT)bool
funcNewMemoizer
funcNewMemoizer[T~string,Vany](expiration,cleanup time.Duration)*Memoizer[T,V]
NewMemoizer instantiates a new Memoizer.
func (Memoizer[T, V])Memoize
func (mMemoizer[T,V])Memoize(keyT,fnfunc() (*cache.Item[V],error)) (*cache.Item[V],error)
Memoize returns the item under a specific key instantly in case the key exists, otherwise returns the results of the given function, making sure that only one execution is in-flight for a given key at a time.
This method is useful for caching the result of a time-consuming operation when is more important to return a slightly outdated result, than to wait for an operation to complete before serving it.
Example
{m:=NewMemoizer[string,any](time.Second,time.Minute)sampleItem:=map[string]any{"foo":"one","bar":"two","baz":"three",}expensiveOp:=func() (*cache.Item[any],error) {// Here we are simulating an expensive operation.time.Sleep(500*time.Millisecond)foo:=FindByKey(sampleItem,func(keystring)bool {returnkey=="foo"})m.Cache.MapToCache(foo,cache.DefaultExpiration)item,err:=m.Cache.Get("foo")iferr!=nil {returnnil,err}returnitem,nil}fmt.Println(m.Cache.List())// Caching the result of some expensive fictive operation result.data,_:=m.Memoize("key1",expensiveOp)fmt.Println(len(m.Cache.List()))item,_:=m.Cache.Get("key1")fmt.Println(item.Val())// Serving the expensive operation result from the cache. This should return instantly.// If it would invoked the expensiveOp function this would be introduced a 500 millisecond latency.data,_=m.Memoize("key1",expensiveOp)fmt.Println(data.Val())}
map[]2oneone
typeNumber
Number is a custom type set of constraints extending the Float and Integer type set from the experimental constraints package.
typeNumberinterface {// contains filtered or unexported methods}
typeRType
RType is a generic struct type used as method receiver on retry operations.
typeRType[Tany]struct {InputT}
func (RType[T])Retry
func (vRType[T])Retry(nint,fnfunc(T)error) (int,error)
Retry tries to invoke the callback function `n` times. It runs until the number of attempts is reached or the returned value of the callback function is nil.
Example
{n:=2idx:=0ForEach([]string{"one","two","three"},func(valstring) {rt:=RType[string]{Input:val}attempts,e:=rt.Retry(n,func(elemstring) (errerror) {iflen(elem)%3!=0 {err=fmt.Errorf("retry failed: number of %d attempts exceeded",n)}returnerr})switchidx {case0:fmt.Println(attempts)case1:fmt.Println(attempts)case2:fmt.Println(attempts)fmt.Println(e)}idx++})}
002retry failed: number of 2 attempts exceeded
func (RType[T])RetryWithDelay
func (vRType[T])RetryWithDelay(nint,delay time.Duration,fnfunc(time.Duration,T)error) (time.Duration,int,error)
RetryWithDelay tries to invoke the callback function `n` times, but with a delay between each call. It runs until the number of attempts is reached or the error return value of the callback function is nil.
Example
{n:=5// In this example we are simulating an external service. In case the response time// exceeds a certain time limit we stop retrying and we are returning an error.services:= []struct {servicestringtime time.Duration}{{service:"AWS1"},{service:"AWS2"},}typeService[T~string]struct {ServiceTTime time.Duration}for_,srv:=rangeservices {r:=random(1,10)// Here we are simulating the response time of the external service// by generating some random duration between 1ms and 10ms.// All the test should pass because all of the responses are inside the predefined limit (10ms).service:=Service[string]{Service:srv.service,Time:time.Duration(r)*time.Millisecond,}rtyp:=RType[Service[string]]{Input:service,}d,att,e:=rtyp.RetryWithDelay(n,20*time.Millisecond,func(d time.Duration,srvService[string]) (errerror) {ifsrv.Time.Milliseconds()>10 {err=fmt.Errorf("retry failed: service time exceeded")}returnerr})fmt.Println(e)fmt.Println(att)fmt.Println(d.Milliseconds())}}
<nil>00
- Request new features or fixopen issues
- Fork the project and makepull requests
- Endre Simo (@simo_endre)
Copyright © 2022 Endre Simo
This software is distributed under the MIT license. See theLICENSE file for the full license text.
About
A comprehensive, reusable and efficient concurrent-safe generics utility functions and data structures library.