fix: orderedstring add performance improvements

This commit is contained in:
Qiu Jian
2020-07-07 01:30:36 +08:00
parent 8c7593d937
commit f0c3b96274
2 changed files with 84 additions and 3 deletions
+23 -3
View File
@@ -29,6 +29,11 @@ func NewSortedStrings(strs []string) SSortedStrings {
}
func Append(ss SSortedStrings, ele ...string) SSortedStrings {
ss = ss.Append(ele...)
return ss
}
func (ss SSortedStrings) Append(ele ...string) SSortedStrings {
if ss == nil {
ss = NewSortedStrings([]string{})
}
@@ -38,14 +43,29 @@ func Append(ss SSortedStrings, ele ...string) SSortedStrings {
continue
}
ss = append(ss, e)
for i := len(ss) - 1; i > pos; i -= 1 {
ss[i] = ss[i-1]
}
copy(ss[pos+1:], ss[pos:])
ss[pos] = e
}
return ss
}
func (ss SSortedStrings) Remove(ele ...string) SSortedStrings {
if ss == nil {
return ss
}
for _, e := range ele {
pos, find := ss.Index(e)
if !find {
continue
}
if pos < len(ss)-1 {
copy(ss[pos:], ss[pos+1:])
}
ss = ss[:len(ss)-1]
}
return ss
}
func (ss SSortedStrings) Index(needle string) (int, bool) {
i := 0
j := len(ss) - 1
@@ -15,6 +15,7 @@
package stringutils2
import (
"reflect"
"testing"
)
@@ -74,3 +75,63 @@ func TestMergeStrings(t *testing.T) {
t.Logf("B: %s", ss2)
t.Logf("%s", m)
}
func TestSortedStringsAppend(t *testing.T) {
cases := []struct {
in []string
ele []string
want SSortedStrings
}{
{
in: []string{"Alpha", "Bravo", "Go"},
ele: []string{"Go2"},
want: []string{"Alpha", "Bravo", "Go", "Go2"},
},
{
in: []string{"Alpha", "Bravo", "Go2"},
ele: []string{"Go"},
want: []string{"Alpha", "Bravo", "Go", "Go2"},
},
{
in: []string{"Alpha", "Bravo", "Go2"},
ele: []string{"Aaaa", "Go"},
want: []string{"Aaaa", "Alpha", "Bravo", "Go", "Go2"},
},
}
for _, c := range cases {
got := NewSortedStrings(c.in).Append(c.ele...)
if !reflect.DeepEqual(c.want, got) {
t.Errorf("want: %s got: %s", c.want, got)
}
}
}
func TestSortedStringsRemove(t *testing.T) {
cases := []struct {
in []string
ele []string
want SSortedStrings
}{
{
in: []string{"Alpha", "Bravo", "Go"},
ele: []string{"Go", "Go2"},
want: []string{"Alpha", "Bravo"},
},
{
in: []string{"Alpha", "Bravo", "Go2"},
ele: []string{"Go"},
want: []string{"Alpha", "Bravo", "Go2"},
},
{
in: []string{"Alpha", "Bravo", "Go", "Go2"},
ele: []string{"Aaaa", "Alpha"},
want: []string{"Bravo", "Go", "Go2"},
},
}
for _, c := range cases {
got := NewSortedStrings(c.in).Remove(c.ele...)
if !reflect.DeepEqual(c.want, got) {
t.Errorf("want: %s got: %s", c.want, got)
}
}
}