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 established and consecrated frameworks like lodash or Apache 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?
- [x] It's concurrent-safe (with the exception of B-tree package)
- [x] Implements a dozens of time related functions like: before, after, delay, memoize, debounce, once, retry
- [x] Rich utility functions to operate with strings
- [x] Very wide range of supported functions to deal with slice and map operations
- [x] Extensive test coverage
- [x] Implements the most used data structures
- [x] Thourough documentation accompanied with examples
$ go get github.com/esimov/gogu
package main
import "github.com/esimov/gogu"
func main() {
// main program
}
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
Map utility functions
Concurrency and time related utility functions
func Abs[T Number](x T) T
Abs returns the absolut value of x.
func After[V constraints.Signed](n *V, fn func())
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) - 1
initVal := 0
fn := func(val int) int {
return val + 1
}
ForEach(sample, func(val int) {
now := time.Now()
After(&length, func() {
<-time.After(10 * time.Millisecond)
initVal = fn(initVal)
after := time.Since(now).Milliseconds()
fmt.Println(after)
})
})
}
10
func Before[S ~string, T any, V constraints.Signed](n *V, c *cache.Cache[S, T], fn func() 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)
var n = 3
sample := []int{1, 2, 3}
ForEach(sample, func(val int) {
fn := func() int {
<-time.After(10 * time.Millisecond)
return n
}
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.
if n > 0 {
val, _ := c.Get("func")
fmt.Println(val)
fmt.Println(res)
}
if n <= 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
func CamelCase[T ~string](str T) 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__"))
}
fooBar
fooBar
fooBar
fooBar
fooBar
fooBar
fooBar
func Capitalize[T ~string](str T) T
Capitalize converts the first letter of the string to uppercase and the remaining letters to lowercase.
func Chunk[T comparable](slice []T, size int) [][]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]]
func Clamp[T Number](num, min, max T) T
Clamp returns a range-limited number between min and max.
func Compare[T comparable](a, b T, comp CompFn[T]) int
Compare compares two values using as comparator the callback function argument.
Example
{
res1 := Compare(1, 2, func(a, b int) bool {
return a < b
})
fmt.Println(res1)
res2 := Compare("a", "b", func(a, b string) bool {
return a > b
})
fmt.Println(res2)
}
1
-1
func Contains[T comparable](slice []T, value T) bool
Contains returns true if the value is present in the collection.
func Delay(delay time.Duration, fn func()) *time.Timer
Delay invokes the callback function with a predefined delay.
Example
{
ch := make(chan struct{})
now := time.Now()
var value uint32
timer := Delay(20*time.Millisecond, func() {
atomic.AddUint32(&value, 1)
ch <- struct{}{}
})
r1 := atomic.LoadUint32(&value)
fmt.Println(r1)
<-ch
if timer.Stop() {
<-timer.C
}
r1 = atomic.LoadUint32(&value)
fmt.Println(r1)
after := time.Since(now).Milliseconds()
fmt.Println(after)
}
0
1
20
func Difference[T comparable](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.
func DifferenceBy[T comparable](s1, s2 []T, fn func(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.
func Drop[T any](slice []T, n int) []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.
func DropWhile[T any](slice []T, fn func(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
```go { res := DropWhile([]string{"a", "aa", "bbb", "ccc"}, func(elem string) bool { return len(elem) > 2 }) fmt.