add show course and map names
This commit is contained in:
36
internal/common/xslices/filter.go
Normal file
36
internal/common/xslices/filter.go
Normal file
@ -0,0 +1,36 @@
|
||||
package xslices
|
||||
|
||||
func Filter[T any](values []T, f func(T) bool) []T {
|
||||
out := make([]T, 0, len(values))
|
||||
for _, value := range values {
|
||||
if f(value) {
|
||||
out = append(out, value)
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func FilterInplace[T any](values []T, match func(T) bool) (newlen int) {
|
||||
next := 0
|
||||
for i := 0; i < len(values); i++ {
|
||||
value := values[i]
|
||||
if !match(value) {
|
||||
continue
|
||||
}
|
||||
|
||||
if next != i {
|
||||
values[next] = value
|
||||
}
|
||||
|
||||
next++
|
||||
}
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
func Not[T any](f func(T) bool) func(T) bool {
|
||||
return func(t T) bool {
|
||||
return !f(t)
|
||||
}
|
||||
}
|
||||
52
internal/common/xslices/filter_test.go
Normal file
52
internal/common/xslices/filter_test.go
Normal file
@ -0,0 +1,52 @@
|
||||
package xslices_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.loyso.art/frx/kurious/internal/common/xslices"
|
||||
)
|
||||
|
||||
func TestFilterInplace(t *testing.T) {
|
||||
tt := []struct {
|
||||
name string
|
||||
in []int
|
||||
check func(int) bool
|
||||
expLen int
|
||||
}{{
|
||||
name: "empty",
|
||||
in: nil,
|
||||
check: nil,
|
||||
expLen: 0,
|
||||
}, {
|
||||
name: "all match",
|
||||
in: []int{1, 2, 3},
|
||||
check: func(int) bool {
|
||||
return true
|
||||
},
|
||||
expLen: 3,
|
||||
}, {
|
||||
name: "all not match",
|
||||
in: []int{1, 2, 3},
|
||||
check: func(int) bool {
|
||||
return false
|
||||
},
|
||||
expLen: 0,
|
||||
}, {
|
||||
name: "some filtered out",
|
||||
in: []int{1, 2, 3, 4},
|
||||
check: func(v int) bool {
|
||||
return v%2 == 0
|
||||
},
|
||||
expLen: 2,
|
||||
}}
|
||||
|
||||
for _, tc := range tt {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
gotLen := xslices.FilterInplace(tc.in, tc.check)
|
||||
if gotLen != tc.expLen {
|
||||
t.Errorf("exp %d got %d", tc.expLen, gotLen)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
7
internal/common/xslices/foreach.go
Normal file
7
internal/common/xslices/foreach.go
Normal file
@ -0,0 +1,7 @@
|
||||
package xslices
|
||||
|
||||
func ForEach[T any](items []T, f func(T)) {
|
||||
for _, item := range items {
|
||||
f(item)
|
||||
}
|
||||
}
|
||||
10
internal/common/xslices/map.go
Normal file
10
internal/common/xslices/map.go
Normal file
@ -0,0 +1,10 @@
|
||||
package xslices
|
||||
|
||||
func Map[T, U any](in []T, f func(T) U) []U {
|
||||
out := make([]U, len(in))
|
||||
for i, value := range in {
|
||||
out[i] = f(value)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user