Jelajahi Sumber

add stringx.FirstN (#914)

Kevin Wan 3 tahun lalu
induk
melakukan
f2612db4b1
3 mengubah file dengan 60 tambahan dan 4 penghapusan
  1. 14 0
      core/stringx/strings.go
  2. 40 0
      core/stringx/strings_test.go
  3. 6 4
      tools/goctl/util/env/env.go

+ 14 - 0
core/stringx/strings.go

@@ -40,6 +40,20 @@ func Filter(s string, filter func(r rune) bool) string {
 	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.
 func HasEmpty(args ...string) bool {
 	for _, arg := range args {

+ 40 - 0
core/stringx/strings_test.go

@@ -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) {
 	cases := []struct {
 		input  []string

+ 6 - 4
tools/goctl/util/env/env.go

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