more helper functions

This commit is contained in:
Timon Ringwald 2022-09-06 01:58:19 +02:00
parent 4f3cf3f537
commit cdb1cf3e03
6 changed files with 87 additions and 18 deletions

View File

@ -20,21 +20,3 @@ func Contains[T comparable](slice []T, value T) bool {
func ContainsCmp[T comparable](slice []T, value T, cmp EqualityComparator[T]) bool {
return IndexOfCmp(slice, value, cmp) != -1
}
func Map[I, O any](slice []I, mapper func(I) O) []O {
ret := make([]O, 0, len(slice))
for _, v := range slice {
ret = append(ret, mapper(v))
}
return ret
}
func Each[T any](slice []T, f func(T)) {
EachIndex(slice, func(_ int, v T) { f(v) })
}
func EachIndex[T any](slice []T, f func(int, T)) {
for i, v := range slice {
f(i, v)
}
}

11
each.go Normal file
View File

@ -0,0 +1,11 @@
package slices
func Each[T any](slice []T, f func(T)) {
EachIndex(slice, func(_ int, v T) { f(v) })
}
func EachIndex[T any](slice []T, f func(int, T)) {
for i, v := range slice {
f(i, v)
}
}

9
flat.go Normal file
View File

@ -0,0 +1,9 @@
package slices
func Flat[T any](s ...[]T) []T {
out := make([]T, 0)
for _, v := range s {
out = append(out, v...)
}
return out
}

9
map.go Normal file
View File

@ -0,0 +1,9 @@
package slices
func Map[I, O any](slice []I, mapper func(I) O) []O {
ret := make([]O, 0, len(slice))
for _, v := range slice {
ret = append(ret, mapper(v))
}
return ret
}

16
of.go Normal file
View File

@ -0,0 +1,16 @@
package slices
func Of[T any](values ...T) []T {
return values
}
// OfMap returns a slice containing the return values of the unmapper function
// applied to any key-value pair in m
// The order is random
func OfMap[K comparable, V, T any](m map[K]V, unmapper func(K, V) T) []T {
out := make([]T, 0, len(m))
for k, v := range m {
out = append(out, unmapper(k, v))
}
return out
}

42
to.go Normal file
View File

@ -0,0 +1,42 @@
package slices
import (
"container/list"
)
// Deref returns a slice containing all dereferenced values of s.
// The returned slice will be a dereferenced and continuous block of memory.
// Nil pointers are ignored.
func Deref[T any](s []*T) []T {
out := make([]T, 0, len(s))
Each(s, func(v *T) {
if v != nil {
out = append(out, *v)
}
})
return out
}
// ToList returns a list.List containing all values of s
func ToList[T any](s []T) *list.List {
l := list.New()
Each(s, func(value T) { l.PushBack(value) })
return l
}
// ToMap returns a map containing all values of s.
// The map key-value pairs are determined by mapper
func ToMap[T any, K comparable, V any](s []T, mapper func(T) (K, V)) map[K]V {
m := map[K]V{}
Each(s, func(value T) {
k, v := mapper(value)
m[k] = v
})
return m
}
// ToStructMap returns a struct{} map containing all values of s as keys.
// It is a shorthand for ToMap(s, func(value T) (T, struct{}) { return value, struct{}{} })
func ToStructMap[T comparable](s []T) map[T]struct{} {
return ToMap(s, func(value T) (T, struct{}) { return value, struct{}{} })
}