3 Commits

Author SHA1 Message Date
26ea846e93 - added FindFirst and FindLast
- removed Search
2024-02-20 16:03:29 +01:00
0592add8ca MapError implemented 2023-03-25 08:52:08 +01:00
ab6e6684f8 added Reduce method 2023-03-09 14:34:44 +01:00
7 changed files with 62 additions and 14 deletions

View File

@ -9,3 +9,22 @@ func Filter[T any](slice []T, f func(T) bool) []T {
} }
return ret return ret
} }
func FindFirst[T any](slice []T, f func(T) bool) (T, bool) {
for _, v := range slice {
if f(v) {
return v, true
}
}
return *new(T), false
}
func FindLast[T any](slice []T, f func(T) bool) (T, bool) {
for i := len(slice); i >= 0; i-- {
v := slice[i]
if f(v) {
return v, true
}
}
return *new(T), false
}

2
go.mod
View File

@ -1,3 +1,5 @@
module git.milar.in/milarin/slices module git.milar.in/milarin/slices
go 1.19 go 1.19
require git.milar.in/milarin/gmath v0.0.3

4
go.sum
View File

@ -1,2 +1,2 @@
git.milar.in/milarin/channel v0.0.7 h1:cVKtwgH/EE7U+XTHcoFCClJ4LR349KanzjX9xKwRcNg= git.milar.in/milarin/gmath v0.0.3 h1:ii6rKNItS55O/wtIFhD1cTN2BMwDZjTBmiOocKURvxM=
git.milar.in/milarin/channel v0.0.7/go.mod h1:We83LTI8S7u7II3pD+A2ChCDWJfCkcBUCUqii9HjTtM= git.milar.in/milarin/gmath v0.0.3/go.mod h1:HDLftG5RLpiNGKiIWh+O2G1PYkNzyLDADO8Cd/1abiE=

12
map.go
View File

@ -7,3 +7,15 @@ func Map[I, O any](slice []I, mapper func(I) O) []O {
} }
return ret return ret
} }
func MapError[I, O any](slice []I, mapper func(I) (O, error)) ([]O, error) {
ret := make([]O, 0, len(slice))
for _, old := range slice {
new, err := mapper(old)
if err != nil {
return nil, err
}
ret = append(ret, new)
}
return ret, nil
}

15
reduce.go Normal file
View File

@ -0,0 +1,15 @@
package slices
import "git.milar.in/milarin/gmath"
func Reduce[T, R any](slice []T, reducer func(current R, v T) R) R {
res := new(R)
Each(slice, func(v T) {
*res = reducer(*res, v)
})
return *res
}
func SumReducer[N gmath.Number](a, b N) N {
return a + b
}

11
reduce_test.go Normal file
View File

@ -0,0 +1,11 @@
package slices
import (
"fmt"
"testing"
)
func TestReduce(t *testing.T) {
s := Of(1, 2, 3)
fmt.Println(Reduce(s, SumReducer[int]))
}

View File

@ -1,11 +0,0 @@
package slices
func Search[T any](slice []T, f func(a, b T) T) T {
if len(slice) == 0 {
return *new(T)
}
value := slice[0]
Each(slice, func(v T) { value = f(value, v) })
return value
}