lol

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 20, 2024 License: MIT Imports: 7 Imported by: 1

README

lol

Go Reference Build Status Coverage Status

👾 Devoted to creating a simple and efficient Go toolbox, and maintaining it continuously.

Installation

go get -u github.com/ifuryst/lol

Quick Start

package main

import (
	"fmt"
	"github.com/ifuryst/lol"
)

func main() {
	res1 := lol.MergeSlice([]int{1, 4, 7}, []int{2, 5, 8}, []int{3, 6, 9})
	res2 := lol.MergeSlice([]int{1}, []int{2, 5, 8}, []int{3, 6}, []int{4, 7, 9, 10})
	fmt.Println(res1)
	fmt.Println(res2)
	// Output:
	// [1 4 7 2 5 8 3 6 9]
	// [1 2 5 8 3 6 4 7 9 10]
}

Usage

For more detailed usage, you can visit the wiki page.

Contributing

Contributions Welcome!

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'feat: add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

License

Released under the MIT License.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs

func Abs[T number](x T) T

Abs returns the absolute value of x.

Special cases are:

Abs(±Inf) = +Inf
Abs(NaN) = NaN

This implementation is from https://go-review.googlesource.com/c/go/+/436296

Example
xFloat64 := Abs(float64(-2))
fmt.Printf("%.1f, %T\n", xFloat64, xFloat64)

yFloat64 := Abs(float64(2))
fmt.Printf("%.1f, %T\n", yFloat64, yFloat64)

xInt := Abs(int(-2))
fmt.Printf("%d, %T\n", xInt, xInt)

yInt := Abs(int(2))
fmt.Printf("%d, %T\n", yInt, yInt)

type int64Type int64
xTypeInt64 := Abs(int64Type(-2))
fmt.Printf("%d, %T\n", xTypeInt64, xTypeInt64)

yTypeInt64 := Abs(int64Type(2))
fmt.Printf("%d, %T\n", yTypeInt64, yTypeInt64)
Output:

2.0, float64
2.0, float64
2, int
2, int
2, lol.int64Type
2, lol.int64Type

func Difference

func Difference[T comparable](s1, s2 []T) []T

Difference returns the difference of s1-s2.

Play: https://go.dev/play/p/fB7HJFYbsCB

Example
res1 := Difference([]int{1, 4, 7, 11}, []int{4, 1, 2})
res2 := Difference([]int{9, 10}, []int{4, 7, 9, 10})
sort.Ints(res1)
sort.Ints(res2)
fmt.Println(res1)
fmt.Println(res2)
Output:

[7 11]
[]

func DoThenRepeat added in v1.2.0

func DoThenRepeat(ctx context.Context, interval time.Duration, fn func(), waitForPrevious bool) func()

DoThenRepeat executes a given function periodically at a specified interval until the context is done. Parameters:

  • ctx: A context to control the lifetime of the function's execution. When the context is canceled, the function stops executing.
  • interval: The duration between consecutive function executions.
  • fn: The function to be executed periodically.
  • waitForPrevious: A boolean flag indicating whether to wait for the previous execution to complete before starting a new one. If true, the function executes sequentially. If false, the function starts a new execution even if the previous one is still running.

Returns a function that blocks until all the function executions are completed.

The function runs asynchronously in a goroutine, and the first execution occurs immediately upon calling DoThenRepeat.

Play: https://go.dev/play/p/aF2fcqmJKAZ

Example
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)

i := atomic.Int32{}
wait := DoThenRepeat(ctx, time.Millisecond*400, func() {
	i.Add(1)
	time.Sleep(300 * time.Millisecond)
}, false)

time.Sleep(1 * time.Second)
cancel()
wait()

fmt.Println(i.Load() >= 2)
Output:

true

func FindSliceDeltas added in v1.1.0

func FindSliceDeltas[T any, K comparable](
	s1, s2 []T, key func(T) K,
	equal func(T, T) bool, options ...FindSliceDeltasOptions[T, K],
) (added, removed, updated, unchanged []T)

FindSliceDeltas finds the added, removed, updated and unchanged items between s1 and s2. The key function is used to get the key of the item, and the equal function is used to compare the item. These two functions are required!

The added, updated, unchanged slice will use s2's item, and the removed slice will use s1's item. if you provide the Copy function in FindSliceDeltasOptions, the all return slice will be copied through the Copy function.

Play: https://go.dev/play/p/1-AFrP7CIGQ

Example
added, removed, updated, unchanged := FindSliceDeltas([]int{1, 4, 7, 11}, []int{4, 1, 2}, func(t int) int {
	return t
}, func(v1 int, v2 int) bool {
	return v1 == v2
}, FindSliceDeltasOptions[int, int]{Compare: func(a, b int) int {
	return a - b
}})
fmt.Println(added)
fmt.Println(removed)
fmt.Println(updated)
fmt.Println(unchanged)
Output:

[2]
[7 11]
[]
[1 4]

func Include

func Include[T comparable](list []T, ele T) bool

Include returns true if the slice includes the element.

Play: https://go.dev/play/p/6VW3_rG4AIX

Example
res1 := Include([]int{1, 7, 3, 4}, 3)
res2 := Include([]string{"1", "7", "3", "4"}, "x")
fmt.Println(res1)
fmt.Println(res2)
Output:

true
false

func Index

func Index[T comparable](list []T, ele T) int

Index returns the index of elements in the slice, or -1 if not found.

Play: https://go.dev/play/p/4ZBiqNvs-Vc

Example
res1 := Index([]int{1, 7, 3, 4, 3}, 3)
res2 := Index([]string{"1", "7", "3", "4"}, "x")
fmt.Println(res1)
fmt.Println(res2)
Output:

2
-1

func Intersection

func Intersection[T comparable](ss ...[]T) []T

Intersection returns the intersection of multiple slices.

Play: https://go.dev/play/p/tqI_pu_-khj

Example
res1 := Intersection([]int{1, 4, 7}, []int{4, 1, 2}, []int{7, 1, 3})
res2 := Intersection([]int{4, 7, 9, 10}, []int{4, 7, 9, 10})
sort.Ints(res1)
sort.Ints(res2)
fmt.Println(res1)
fmt.Println(res2)
Output:

[1]
[4 7 9 10]

func Keys

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

Keys creates an array of the map keys.

Play: https://go.dev/play/p/JlVhmI6ThnL

Example
res1 := Keys(map[int]struct{}{
	1: {},
	7: {},
	3: {},
	4: {},
})
sort.Ints(res1)
res2 := Keys(map[string]struct{}{
	"a": {},
	"b": {},
	"1": {},
	"2": {},
})
sort.Strings(res2)
fmt.Println(res1)
fmt.Println(res2)
Output:

[1 3 4 7]
[1 2 a b]

func LastIndex

func LastIndex[T comparable](list []T, ele T) int

LastIndex is same as Index, but it returns the last index.

Play: https://go.dev/play/p/TL2YNWHvDqw

Example
res1 := LastIndex([]int{1, 7, 3, 4, 3}, 3)
res2 := LastIndex([]string{"1", "7", "3", "4"}, "x")
fmt.Println(res1)
fmt.Println(res2)
Output:

4
-1

func Map

func Map[T any](list []T, fn func(v T) T) []T

Map maps a function over a slice.

Play: https://go.dev/play/p/ePBYrs1YqDz

Example
res := Map([]int{1, 3, 5}, func(i int) int { return i * 2 })
fmt.Println(res)
Output:

[2 6 10]

func MapTo

func MapTo[T any, R any](list []T, fn func(v T) R) []R

MapTo is same as Map, but it can return another type of slice.

Special case: when fn is nil, it returns the empty slice.

PLay: https://go.dev/play/p/wClBNz0Fjxt

Example
type user struct {
	name string
	age  uint8
}
res := MapTo([]user{
	{"Heisenberg", 35},
	{"Hank", 32},
	{"Saul", 33},
}, func(u user) string { return u.name })
fmt.Println(res)
Output:

[Heisenberg Hank Saul]

func Max

func Max[T number](a, b T) T

Max returns the largest of x and y.

Example
fmt.Println(Max(3, 1))
fmt.Println(Max(3.3, -1.0))
Output:

3
3.3

func MergeSlice

func MergeSlice[T any](ss ...[]T) []T

MergeSlice merges multiple slices without removing duplicates or shuffling the elements.

Play: https://go.dev/play/p/ARhoTg83WK8

Example
res1 := MergeSlice([]int{1, 4, 7}, []int{2, 5, 8}, []int{3, 6, 9})
res2 := MergeSlice([]int{1}, []int{2, 5, 8}, []int{3, 6}, []int{4, 7, 9, 10})
fmt.Println(res1)
fmt.Println(res2)
Output:

[1 4 7 2 5 8 3 6 9]
[1 2 5 8 3 6 4 7 9 10]

func Min

func Min[T number](a, b T) T

Min returns the smallest of x and y.

Example
fmt.Println(Min(3, 1))
fmt.Println(Min(3.3, -1.0))
Output:

1
-1

func NewFalse

func NewFalse() *bool

NewFalse returns a pointer to a new bool with false.

func NewTrue

func NewTrue() *bool

NewTrue returns a pointer to a new bool with true.

Example
fmt.Println(*NewTrue())
fmt.Println(*NewFalse())
Output:

true
false

func Reduce

func Reduce[T any, R any](list []T, fn func(sum R, item T, index int) R, initial R) R

Reduce accumulates and combines elements through a fn into a single value.

Special case: when fn is nil, it returns the initial value

Play: https://go.dev/play/p/gI8Mcvk4NGr

Example
res1 := Reduce([]int{1, 7, 3, 4}, func(s float64, v, i int) float64 {
	return s * float64(v)
}, 2)
res2 := Reduce([]string{"1", "7", "3", "4"}, func(s, v string, i int) string {
	return fmt.Sprintf("%s %d.%s", s, i, v)
}, "start:")
fmt.Println(res1)
fmt.Println(res2)
Output:

168
start: 0.1 1.7 2.3 3.4

func ReduceRight

func ReduceRight[T any, R any](list []T, fn func(sum R, item T, index int) R, initial R) R

ReduceRight is like the Reduce, but the order is reserve.

Special case: when fn is nil, it returns the initial value

Play: https://go.dev/play/p/n1rGGeg1KFf

Example
res1 := ReduceRight([]int{1, 7, 3, 4}, func(s float64, v, i int) float64 {
	return s * float64(v)
}, 2)
res2 := ReduceRight([]string{"1", "7", "3", "4"}, func(s, v string, i int) string {
	return fmt.Sprintf("%s %d.%s", s, i, v)
}, "reverse:")
fmt.Println(res1)
fmt.Println(res2)
Output:

168
reverse: 3.4 2.3 1.7 0.1

func RepeatTask added in v1.2.0

func RepeatTask(ctx context.Context, interval time.Duration, fn func(), waitForPrevious bool) func()

RepeatTask executes a given function periodically at a specified interval until the context is done. Parameters:

  • ctx: A context to control the lifetime of the function's execution. When the context is canceled, the function stops executing.
  • interval: The duration between consecutive function executions.
  • fn: The function to be executed periodically.
  • waitForPrevious: A boolean flag indicating whether to wait for the previous execution to complete before starting a new one. If true, the function executes sequentially. If false, the function starts a new execution even if the previous one is still running.

Returns a function that blocks until all the function executions are completed.

The function runs asynchronously in a goroutine, and the first execution occurs after the first interval has elapsed.

Play: https://go.dev/play/p/ldnDL__QNlh

Example
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)

i := atomic.Int32{}
wait := RepeatTask(ctx, time.Millisecond*400, func() {
	i.Add(1)
	time.Sleep(300 * time.Millisecond)
}, false)

time.Sleep(1 * time.Second)
cancel()
wait()

fmt.Println(i.Load() >= 2)
Output:

true

func Shuffle

func Shuffle[T any](list []T)

Shuffle shuffles a slice for random order. Implement based on rand.Shuffle

Play: https://go.dev/play/p/A2yeiJDWIHp

Example
s := []string{"a", "b", "c", "d"}
Shuffle(s)
fmt.Println(s)
Output:

func SortSlice

func SortSlice[S ~[]E, E constraints.Ordered](s S)

SortSlice sorts a slice. Just a wrapper for slices.Sort.

Example
s := []float64{3, 6, 1, math.NaN(), 9, math.NaN()}
fmt.Println(s)
SortSlice(s)
fmt.Println(s)
Output:

[3 6 1 NaN 9 NaN]
[NaN NaN 1 3 6 9]

func Union

func Union[T comparable](ss ...[]T) []T

Union returns the union of multiple slices.

func UniqSlice

func UniqSlice[T comparable](ss ...[]T) []T

UniqSlice merges multiple slices with removing duplicates the elements.

Play: https://go.dev/play/p/clvg0gFoBQs

Example
res1 := UniqSlice([]int{1, 4, 7}, []int{4, 1, 2}, []int{7, 1, 3})
res2 := UniqSlice([]int{4, 7, 9, 10})
fmt.Println(res1)
fmt.Println(res2)
Output:

[1 4 7 2 3]
[4 7 9 10]

func Values

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

Values creates an array of the map values.

Play: https://go.dev/play/p/YQrxuIzbimT

Example
res1 := Values(map[int]int{
	1: 3,
	7: 5,
	3: 9,
	4: 7,
})
sort.Ints(res1)
res2 := Values(map[int]string{
	1: "3",
	7: "5",
	3: "9",
	4: "7",
})
sort.Strings(res2)
fmt.Println(res1)
fmt.Println(res2)
Output:

[3 5 7 9]
[3 5 7 9]

Types

type FindSliceDeltasOptions added in v1.1.0

type FindSliceDeltasOptions[T any, K comparable] struct {
	// Copy realizes deep copy, confirm the FindSliceDeltas return the new slice
	Copy func(T) T

	// Compare should return a negative number when a < b, a positive number when
	// a > b and zero when a == b.
	Compare func(a, b T) int
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL