From c7f5aad83a461bd22d36744c10dc2f0968abf2db Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Mon, 16 Aug 2021 12:08:33 +0800 Subject: [PATCH] add stringx.FirstN with ellipsis (#916) --- core/stringx/strings.go | 8 ++++++-- core/stringx/strings_test.go | 25 ++++++++++++++++++++----- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/core/stringx/strings.go b/core/stringx/strings.go index 4a89d465..18c8c215 100644 --- a/core/stringx/strings.go +++ b/core/stringx/strings.go @@ -41,12 +41,16 @@ func Filter(s string, filter func(r rune) bool) string { } // FirstN returns first n runes from s. -func FirstN(s string, n int) string { +func FirstN(s string, n int, ellipsis ...string) string { var i int for j := range s { if i == n { - return s[:j] + ret := s[:j] + for _, each := range ellipsis { + ret += each + } + return ret } i++ } diff --git a/core/stringx/strings_test.go b/core/stringx/strings_test.go index fe118e5f..1e88b829 100644 --- a/core/stringx/strings_test.go +++ b/core/stringx/strings_test.go @@ -94,10 +94,11 @@ func TestFilter(t *testing.T) { func TestFirstN(t *testing.T) { tests := []struct { - name string - input string - n int - expect string + name string + input string + n int + ellipsis string + expect string }{ { name: "english string", @@ -105,6 +106,13 @@ func TestFirstN(t *testing.T) { n: 8, expect: "anything", }, + { + name: "english string with ellipsis", + input: "anything that we use", + n: 8, + ellipsis: "...", + expect: "anything...", + }, { name: "english string more", input: "anything that we use", @@ -117,6 +125,13 @@ func TestFirstN(t *testing.T) { n: 2, expect: "我是", }, + { + name: "chinese string with ellipsis", + input: "我是中国人", + n: 2, + ellipsis: "...", + expect: "我是...", + }, { name: "chinese string", input: "我是中国人", @@ -127,7 +142,7 @@ func TestFirstN(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.expect, FirstN(test.input, test.n)) + assert.Equal(t, test.expect, FirstN(test.input, test.n, test.ellipsis)) }) } }