garray

package
v0.0.0-...-d5aba35 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2024 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apply

func Apply[S ~[]T, T any](l S, fun func(T) error) error

Apply a function to each item of a slice

Example
numList := []int{1, 2, 3, 4, 5, 6}
double := func(n int) error {
	fmt.Print(n*2, " ")
	return nil
}

err := Apply(numList, double)
if err != nil {
	fmt.Println("Error Occured")
}
// expected output to be array elements multiplied by 2
Output:

2 4 6 8 10 12

func ApplyI

func ApplyI[S ~[]T, T any](l S, fun func(int) error) error
Example
words := []string{"bar", "foo"}
var capitalize = func(i int) error {
	words[i] = strings.ToUpper(words[i])
	return nil
}

err := ApplyI(words, capitalize) // all elements capitalized
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%v\n", words)
Output:

[BAR FOO]

func Average

func Average[S ~[]T, T Number](l S) T

Calculate the average of a slice of numbers

func Concat

func Concat[S ~[]T, T any](slices_ ...S) S

copy the contents of all slices_, returns a new slice

func Contains

func Contains[S ~[]T, T comparable](l S, v T) bool

check if l contains v

func Count

func Count[S ~[]T, T comparable](s S, v T) int
Example
l := []int{1, 0, 1, 0, 1}
fmt.Println(Count(l, 1))
Output:

3

func CountIf

func CountIf[T comparable](s slice[T], pred func(v T) bool) int
Example
l := []int{1, 2, 3, 4, 5}
fmt.Println(CountIf(l, func(i int) bool { return i%2 == 0 }))
Output:

2

func Filter

func Filter[Src any](l []Src, f func(Src) bool) (result []Src)

Filter selects items that f() returns true

Example
lst := []int{1, 2, 3, 4, 5, 6}
isEven := func(n int) bool { return n%2 == 0 } // expected filtered array of even numbers

evens := Filter(lst, isEven)
fmt.Println(evens)
Output:

[2 4 6]

func FilterI

func FilterI[Src any](l []Src, f func(i int) bool) (result []Src)

FilterI selects items that f() returns true

Example
lst := []string{"apple", "banana", "cherry", "grape"}
firstTwoItems := func(i int) bool {
	return i < 2 // expected Filtered array of first two items from the list
}

result := FilterI(lst, firstTwoItems)
fmt.Println(result)
Output:

[apple banana]

func FilterIE

func FilterIE[Src any](l []Src, f func(i int) (bool, error)) (result []Src, err error)

FilterIE selects items that f() returns true

Example
nums := []int{1, 2, 3, 4, 5}

evenNums := func(i int) (bool, error) {
	return nums[i]%2 == 0, nil // expected filterd array with only even numbers
}

filteredNums, _ := FilterIE(nums, evenNums)
fmt.Println(filteredNums)
Output:

[2 4]

func FindIf

func FindIf[S ~[]T, T any](l S, pred func(i int) bool) int

FindIf finds the position of an matching element. Its use case is the same as IndexWhere, except that you don't have to specify the type of the elements. (sometimes the type is very long, or it is an anonymous/temporary type that you have to repeat the definition.) It passes each index of l to pred() and returns the first i which pred(i) is true. I find it interestingly handful :) It opens a new way to generics programming that does not support lambda expression.

Example
list := []int{1, 2, 3, 4, 5}
pos := FindIf(list, func(i int) bool {
	return list[i] == 3
})
fmt.Println(pos)
Output:

2

func First

func First[S ~[]T, T any](l S, pred func(T) bool) (T, bool)

find first matching element

func GroupBy

func GroupBy[T any, Slice ~[]T, R any, Key comparable](a Slice, keyF func(v T) Key, resultF func(T) R) map[Key][]R

group a slice of T by a key, resulting groups of slice of R. For incomparable keys, please fmt.Sprintf it to a string

Example
a := []string{`Jack`, `Mike`, `Jones`, `Janes`, `Tom`, `Terry`}
m := GroupBy(a, func(s string) string { return string(s[0:1]) }, func(s string) string { return strings.ToLower(s) })
fmt.Print(m)
Output:

map[J:[jack jones janes] M:[mike] T:[tom terry]]

func GroupByP

func GroupByP[T any, Slice ~[]T, R any, Key comparable](a Slice, keyF func(v *T) Key, resultF func(*T) R) map[Key][]R

group a slice of T by a key, resulting groups of slice of R. For incomparable keys, please fmt.Sprintf it to a string

Example
a := []string{`Jack`, `Mike`, `Jones`, `Janes`, `Tom`, `Terry`}
m := GroupByP(a, func(s *string) string { return string((*s)[0:1]) }, func(s *string) string { return strings.ToLower(*s) })
fmt.Print(m)
Output:

map[J:[jack jones janes] M:[mike] T:[tom terry]]

func IndexOf

func IndexOf[S ~[]T, T comparable](l S, v T) int

find the position of an element

func IndexWhere

func IndexWhere[S ~[]T, T any](l S, pred func(T) bool) int

find the position of an matching element

func IndexWhereP

func IndexWhereP[S ~[]T, T any](l S, pred func(*T) bool) int

like IndexWhere but parses arguments using pointers, to avoid copying large structs and improve performance

func Last

func Last[S ~[]T, T any](l S, pred func(T) bool) (T, bool)

find last matching element

func LastIndexOf

func LastIndexOf[S ~[]T, T comparable](l S, v T) int

find the last position of an element

func LastIndexWhere

func LastIndexWhere[S ~[]T, T any](l S, pred func(T) bool) int

find the last position of an matching element

func LastIndexWhereP

func LastIndexWhereP[S ~[]T, T any](l S, pred func(*T) bool) int

like LastIndexWhere but parses arguments using pointers, to avoid copying large structs and improve performance

func Map

func Map[Src any, Dst any](l []Src, f func(Src) Dst) []Dst

like LINQ.Select, map a slice to another slice

func MapE

func MapE[Src any, Dst any](l []Src, f func(Src) (Dst, error)) (result []Dst, err error)

func MapI

func MapI[Src any, Dst any](l []Src, f func(i int) Dst) []Dst

func MapIE

func MapIE[Src any, Dst any](l []Src, f func(i int) (Dst, error)) (result []Dst, err error)
Example
type student struct {
	name string
	age  int
}

students := []student{{`Jack`, 10}, {`Mike`, 20}, {`Rose`, 15}}

studentAges, err := ToMapIE(students,
	func(i int) (string, error) { return students[i].name, nil },
	func(i int) (int, error) { return students[i].age, nil })
if err != nil {
	fmt.Print(err)
} else {
	fmt.Print(studentAges)
}
Output:

map[Jack:10 Mike:20 Rose:15]

func Max

func Max[S ~[]T, T Number](s S) T
Example
// Finding the maximum element of a slice of integers
max := Max([]int{10, -20, 5, 15, 30, -25})
fmt.Println(max)
Output:

30
Example (PanicsOnEmptySlice)
// Trying to find the maximum element of an empty slice should panic
defer func() {
	if r := recover(); r == nil {
		fmt.Println(`Max didn't panic`)
	} else {
		fmt.Println(r)
	}
}()
Max([]int{})
Output:

Max: empty slice

func MaxBy

func MaxBy[S ~[]T, T any, N Number](s S, selector func(T) N) N
Example
// Finding the maximum length string from a slice of strings
maxLen := MaxBy([]string{`apple`, `banana`, `cherry`, `date`}, func(s string) int {
	return len(s)
})
fmt.Println(maxLen)
Output:

6

func MaxIndex

func MaxIndex[S ~[]T, T any, N Number](s S, selector func(int) N) (result int)
Example
// Finding the index of the maximum element in a slice of integers
maxIndex := MaxIndex([]int{10, -20, 5, 15, 30, -25}, func(i int) int {
	return []int{10, -20, 5, 15, 30, -25}[i]
})
fmt.Println(maxIndex)
Output:

4
Example (Emtpy)
// Trying to find the index of the maximum element in an empty slice should return -1
maxIndex := MaxIndex([]int{}, func(i int) int {
	return []int{}[i]
})
fmt.Println(maxIndex)
Output:

-1

func Min

func Min[S ~[]T, T Number](s S) T
Example
// Finding the minimum element of a slice of floats
min := Min([]float64{3.14, 2.71, 0.0, -1.0, 1.5, -2.0})
fmt.Println(min)
Output:

-2

func MinBy

func MinBy[S ~[]T, T any, N Number](s S, selector func(T) N) N
Example
// Finding the minimum even number from a slice of integers
minEven := MinBy([]int{3, 6, -1, 0, 8, 7, 9}, func(n int) int {
	if n%2 == 0 {
		return n
	} else {
		return math.MaxInt32
	}
})
fmt.Println(minEven)
Output:

0

func MinIndex

func MinIndex[S ~[]T, T any, N Number](s S, selector func(int) N) (result int)
Example
// Finding the index of the maximum element in a slice of integers
maxIndex := MinIndex([]int{10, -20, 5, 15, 30, -25}, func(i int) int {
	return []int{10, -20, 5, 15, 30, -25}[i]
})
fmt.Println(maxIndex)
Output:

5

func OrderBy

func OrderBy[T any, V constraints.Ordered](l []T, selector func(T) V) *sortableBy[T, V]
Example
type Person struct {
	Name string
	Age  int
}
l := []Person{
	{"Alice", 32},
	{"Bob", 22},
	{"Charlie", 42},
	{"David", 27},
}
ordered := OrderBy(l, func(p Person) int { return p.Age })
sort.Sort(ordered)
for _, p := range ordered.slice {
	fmt.Println(p.Name, p.Age)
}
Output:

Bob 22
David 27
Alice 32
Charlie 42

func OrderByDescending

func OrderByDescending[T any, V constraints.Ordered](l []T, selector func(T) V) *sortableByDescending[T, V]
Example
type Product struct {
	Name  string
	Price float64
}
l := []Product{
	{"Laptop", 999.99},
	{"Mouse", 19.99},
	{"Keyboard", 49.99},
	{"Headphones", 79.99},
}
ordered := OrderByDescending(l, func(p Product) float64 { return p.Price })
sort.Sort(ordered)
for _, p := range ordered.slice {
	fmt.Println(p.Name, p.Price)
}
Output:

Laptop 999.99
Headphones 79.99
Keyboard 49.99
Mouse 19.99

func Paginate

func Paginate[S ~[]T, T any](s S, pageSize int, page int) S
Example
l := []int{1, 2, 3, 4, 5, 6, 7, 8}
i := 0
for p := Paginate(l, 3, i); len(p) > 0; {
	fmt.Println(p)
	i++
	p = Paginate(l, 3, i)
}
Output:

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

func Pop

func Pop[S ~[]T, T any](s S) (S, T)

caution should be taken: push/pop may cause multiple slices share the same underlying memory buffer

func PopHead

func PopHead[S ~[]T, T any](s S) (S, T)

func Push

func Push[S ~[]T, T any](s S, v T) S

caution should be taken: push/pop may cause multiple slices share the same underlying memory buffer

func PushHead

func PushHead[S ~[]T, T any](s S, v T) S

func Remove

func Remove[S ~[]T, T comparable](l S, v T) (result S, deleted int)

Remove matching items.

func RemoveIf

func RemoveIf[S ~[]T, T any](l S, pred func(i int) bool) (result S, deleted int)

RemoveIf removes matching items.

Example
list := []int{1, 2, 3, 1, 2, 3, 1, 2, 3}
result, deleted := RemoveIf(list, func(i int) bool {
	return list[i] == 2
})
fmt.Println(result, deleted)
Output:

[1 3 1 3 1 3] 3

func Repeat

func Repeat[T any](v T, n int) []T
Example
fmt.Println(Repeat(1, 6))
Output:

[1 1 1 1 1 1]

func Reverse

func Reverse[S ~[]T, T any](s S)
Example
l := []int{1, 2, 3, 4}
Reverse(l)
fmt.Println(l)
l = []int{1, 2, 3}
Reverse(l)
fmt.Println(l)
Output:

[4 3 2 1]
[3 2 1]

func ShallowCopy

func ShallowCopy[T any](s slice[T]) slice[T]

func Sort

func Sort[T constraints.Ordered](l []T)
Example
l := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
Sort(l)
fmt.Println(l)
Output:

[1 1 2 3 3 4 5 5 5 6 9]

func SortBy

func SortBy[T any, V constraints.Ordered](l []T, selector func(T) V)
Example
type Person struct {
	Name string
	Age  int
}
l := []Person{
	{"Alice", 32},
	{"Bob", 22},
	{"Charlie", 42},
	{"David", 27},
}
SortBy(l, func(p Person) int { return p.Age })
for _, p := range l {
	fmt.Println(p.Name, p.Age)
}
Output:

Bob 22
David 27
Alice 32
Charlie 42

func SortByComparer

func SortByComparer[T any](l []T, less func(T, T) bool)

func SortByDescending

func SortByDescending[T any, V constraints.Ordered](l []T, selector func(T) V)
Example
type Product struct {
	Name  string
	Price float64
}
l := []Product{
	{"Laptop", 999.99},
	{"Mouse", 19.99},
	{"Keyboard", 49.99},
	{"Headphones", 79.99},
}
SortByDescending(l, func(p Product) float64 { return p.Price })
for _, p := range l {
	fmt.Println(p.Name, p.Price)
}
Output:

Laptop 999.99
Headphones 79.99
Keyboard 49.99
Mouse 19.99

func SortDescending

func SortDescending[T constraints.Ordered](l []T)
Example
l := []string{"pineapple", "apple", "banana", "pear", "cherry", "orange"}
SortDescending(l)
fmt.Println(l)
Output:

[pineapple pear orange cherry banana apple]

func Sortable

func Sortable[T constraints.Ordered](l []T) sortable[T]

func SortableDescending

func SortableDescending[T constraints.Ordered](l []T) sortableDescending[T]

func Sum

func Sum[S ~[]T, T Number](l S) T

Sum a slice of numbers

func SumBy

func SumBy[S ~[]V, V any, T Number](l S, selector func(V) T) T

Sum a slice by a selector

Example
type student struct {
	name string
	age  int
}
students := []student{{`Jack`, 10}, {`Mike`, 20}, {`Rose`, 15}}

totalAge := SumBy(students, func(s student) int {
	return s.age
})
fmt.Println(totalAge)
Output:

45

func SumByI

func SumByI[S ~[]V, V any, T Number](l S, selector func(i int) T) T

Sum a slice using an index iterator

Example
type student struct {
	name string
	age  int
}
students := []student{{`Jack`, 10}, {`Mike`, 20}, {`Rose`, 15}}

totalAge := SumByI(students, func(i int) int {
	return students[i].age
})
fmt.Println(totalAge)
Output:

45

func SumByP

func SumByP[S ~[]V, V any, T Number](l S, selector func(*V) T) T

Sum a slice by a pointer selector

Example
type student struct {
	name string
	age  int
}
students := []student{{`Jack`, 10}, {`Mike`, 20}, {`Rose`, 15}}

totalAge := SumByP(students, func(s *student) int {
	return s.age
})
fmt.Println(totalAge)
Output:

45

func ToMapI

func ToMapI[T any, K comparable, V any](
	list []T, keyF func(i int) K, valF func(i int) V) (map[K]V, error)

func ToMapIE

func ToMapIE[T any, K comparable, V any](
	list []T, keyF func(i int) (K, error), valF func(i int) (V, error)) (map[K]V, error)

Types

type Number

type Number interface {
	constraints.Integer | constraints.Float | time.Duration
}

Jump to

Keyboard shortcuts

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