Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions core/stringx/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package stringx
import (
"errors"
"slices"
"strings"
"unicode"

"github.com/zeromicro/go-zero/core/lang"
Expand All @@ -21,20 +22,14 @@ func Contains(list []string, str string) bool {
return slices.Contains(list, str)
}

// Filter filters chars from s with given filter function.
func Filter(s string, filter func(r rune) bool) string {
var n int
chars := []rune(s)
for i, x := range chars {
if n < i {
chars[n] = x
// Filter filters chars from s with given remove function.
func Filter(s string, remove func(r rune) bool) string {
return strings.Map(func(r rune) rune {
if remove(r) {
return -1
}
if !filter(x) {
n++
}
}

return string(chars[:n])
return r
}, s)
}

// FirstN returns first n runes from s.
Expand Down
18 changes: 18 additions & 0 deletions core/stringx/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,24 @@ func TestFilter(t *testing.T) {
}
}

func BenchmarkFilter(b *testing.B) {
b.Run("true", func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
Filter(`ab,cd,ef`, func(r rune) bool { return r == ',' })
}
})

b.Run("false", func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
Filter(`ab,cd,ef`, func(r rune) bool { return r == '!' })
}
})
}

func TestFirstN(t *testing.T) {
tests := []struct {
name string
Expand Down
Loading