add show course and map names

This commit is contained in:
Aleksandr Trushkin
2024-01-08 18:31:35 +03:00
parent 48f5d80f7a
commit 2c0564f68c
22 changed files with 166 additions and 90 deletions

View 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)
}
}

View 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)
}
})
}
}

View File

@ -0,0 +1,7 @@
package xslices
func ForEach[T any](items []T, f func(T)) {
for _, item := range items {
f(item)
}
}

View 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
}