Skip to content

Commit ceaa9f7

Browse files
authored
refactor(strung): unique strings (#16)
1 parent f1b02e9 commit ceaa9f7

File tree

2 files changed

+40
-7
lines changed

2 files changed

+40
-7
lines changed

strung/strung.go

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,7 @@ package strung
33

44
import "strings"
55

6-
// TrimAround trims characters around string
7-
//
8-
// Example:
9-
//
10-
// ```go
11-
// v := TrimAround([]string{" ADD ", " 1 ", " AND ", " 2 "}) // v = []string{"ADD", "1", "AND", "2"}
12-
// ```.
6+
// TrimAround trims characters around string.
137
func TrimAround(v []string, cutset string) []string {
148
var trimmed []string
159

@@ -19,3 +13,20 @@ func TrimAround(v []string, cutset string) []string {
1913

2014
return trimmed
2115
}
16+
17+
// Unique removes duplicated strings from a slice, preserving order.
18+
func Unique(slice []string) []string {
19+
var (
20+
seen = make(map[string]struct{}, len(slice))
21+
result = make([]string, 0, len(slice))
22+
)
23+
24+
for _, v := range slice {
25+
if _, exists := seen[v]; !exists {
26+
seen[v] = struct{}{}
27+
result = append(result, v)
28+
}
29+
}
30+
31+
return result
32+
}

strung/strung_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,25 @@ func TestTrimAround(t *testing.T) {
3636
})
3737
}
3838
}
39+
40+
func TestUnique(t *testing.T) {
41+
tests := []struct {
42+
name string
43+
slice []string
44+
want []string
45+
}{
46+
{
47+
name: "unique strings",
48+
slice: []string{"a", "b", "a", "c"},
49+
want: []string{"a", "b", "c"},
50+
},
51+
}
52+
for _, tt := range tests {
53+
t.Run(tt.name, func(t *testing.T) {
54+
got := strung.Unique(tt.slice)
55+
if slices.Compare(got, tt.want) != 0 {
56+
t.Errorf("Unique() = %v, want %v", got, tt.want)
57+
}
58+
})
59+
}
60+
}

0 commit comments

Comments
 (0)