add stringx.FirstN (#914)

master
Kevin Wan 3 years ago committed by GitHub
parent a21ff71373
commit f2612db4b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -40,6 +40,20 @@ func Filter(s string, filter func(r rune) bool) string {
return string(chars[:n]) return string(chars[:n])
} }
// FirstN returns first n runes from s.
func FirstN(s string, n int) string {
var i int
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
// HasEmpty checks if there are empty strings in args. // HasEmpty checks if there are empty strings in args.
func HasEmpty(args ...string) bool { func HasEmpty(args ...string) bool {
for _, arg := range args { for _, arg := range args {

@ -92,6 +92,46 @@ func TestFilter(t *testing.T) {
} }
} }
func TestFirstN(t *testing.T) {
tests := []struct {
name string
input string
n int
expect string
}{
{
name: "english string",
input: "anything that we use",
n: 8,
expect: "anything",
},
{
name: "english string more",
input: "anything that we use",
n: 80,
expect: "anything that we use",
},
{
name: "chinese string",
input: "我是中国人",
n: 2,
expect: "我是",
},
{
name: "chinese string",
input: "我是中国人",
n: 10,
expect: "我是中国人",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.expect, FirstN(test.input, test.n))
})
}
}
func TestRemove(t *testing.T) { func TestRemove(t *testing.T) {
cases := []struct { cases := []struct {
input []string input []string

@ -10,10 +10,12 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/vars" "github.com/tal-tech/go-zero/tools/goctl/vars"
) )
const bin = "bin" const (
const binGo = "go" bin = "bin"
const binProtoc = "protoc" binGo = "go"
const binProtocGenGo = "protoc-gen-go" binProtoc = "protoc"
binProtocGenGo = "protoc-gen-go"
)
// LookUpGo searches an executable go in the directories // LookUpGo searches an executable go in the directories
// named by the GOROOT/bin or PATH environment variable. // named by the GOROOT/bin or PATH environment variable.

Loading…
Cancel
Save