Skip to content

Commit

Permalink
fix(torbiak#38): add a guard for slices with length 0
Browse files Browse the repository at this point in the history
When the slice's length is 0, should directly return to prevent false
result or slice out of bounds runtime error
  • Loading branch information
Silentroar authored and Silentroar committed May 31, 2022
1 parent 052bf30 commit 0ed51a7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
4 changes: 4 additions & 0 deletions ex4.5/unique.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
package unique

func unique(strs []string) []string {
if len(strs) == 0 {
return strs
}

w := 0 // index of last written string
for _, s := range strs {
if strs[w] == s {
Expand Down
21 changes: 16 additions & 5 deletions ex4.5/unique_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,21 @@ import (
)

func TestUnique(t *testing.T) {
s := []string{"a", "a", "b", "c", "c", "c", "d", "d", "e"}
got := unique(s)
want := []string{"a", "b", "c", "d", "e"}
if !reflect.DeepEqual(got, want) {
t.Errorf("got %v, want %v", got, want)
ss := [][]string{
{"a", "a", "b", "c", "c", "c", "d", "d", "e"},
{},
}

want := [][]string{
{"a", "b", "c", "d", "e"},
{},
}

for i, s := range ss {
got := unique(s)
if !reflect.DeepEqual(got, want[i]) {
t.Errorf("got %v, want %v", got, want[i])
}
}

}

0 comments on commit 0ed51a7

Please sign in to comment.