64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
package q5
|
|
|
|
func Map[T any](arr []T, cb func(T) T) []T {
|
|
newList := []T{}
|
|
for _, val := range arr {
|
|
newList = append(newList, cb(val))
|
|
}
|
|
return newList
|
|
}
|
|
|
|
func Reduce[T any](arr []T, cb func(T, T) T, initVal *T) T {
|
|
var result T
|
|
if initVal != nil {
|
|
result = *initVal
|
|
}
|
|
if len(arr) > 0 {
|
|
if initVal == nil {
|
|
result = arr[0]
|
|
for i := 1; i < len(arr); i++ {
|
|
result = cb(result, arr[i])
|
|
}
|
|
} else {
|
|
for i := 0; i < len(arr); i++ {
|
|
result = cb(result, arr[i])
|
|
}
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func Filter[T any](arr []T, cb func(T) bool) []T {
|
|
newList := []T{}
|
|
for _, val := range arr {
|
|
if cb(val) {
|
|
newList = append(newList, val)
|
|
}
|
|
}
|
|
return newList
|
|
}
|
|
|
|
func Max[T string | int | int32 | int64 | float32 | float64](a T, b T) T {
|
|
if a < b {
|
|
return b
|
|
} else {
|
|
return a
|
|
}
|
|
}
|
|
|
|
func Min[T string | int | int32 | int64 | float32 | float64](a T, b T) T {
|
|
if a < b {
|
|
return a
|
|
} else {
|
|
return b
|
|
}
|
|
}
|
|
|
|
func ToInterfaces[T any](values []T) []interface{} {
|
|
result := []interface{}{}
|
|
for _, val := range values {
|
|
result = append(result, val)
|
|
}
|
|
return result
|
|
}
|