From 6ffc6056c42b92decc61bbb168e94a800e98dc28 Mon Sep 17 00:00:00 2001 From: Andrey Smirnov Date: Fri, 24 Jan 2014 17:45:16 +0400 Subject: [PATCH] StrSlice deduplication. --- utils/list.go | 26 ++++++++++++++++++++++++++ utils/list_test.go | 9 +++++++++ 2 files changed, 35 insertions(+) diff --git a/utils/list.go b/utils/list.go index a27ed109..602c07df 100644 --- a/utils/list.go +++ b/utils/list.go @@ -75,3 +75,29 @@ func StrMapSortedKeys(m map[string]string) []string { sort.Strings(keys) return keys } + +// StrSliceDeduplicate removes dups in slice +func StrSliceDeduplicate(s []string) []string { + l := len(s) + if l < 2 { + return s + } + if l == 2 { + if s[0] == s[1] { + return s[0:1] + } + return s + } + + found := make(map[string]bool, l) + j := 0 + for i, x := range s { + if !found[x] { + found[x] = true + s[j] = s[i] + j++ + } + } + + return s[:j] +} diff --git a/utils/list_test.go b/utils/list_test.go index 31864ecb..9eaad39f 100644 --- a/utils/list_test.go +++ b/utils/list_test.go @@ -47,3 +47,12 @@ func (s *ListSuite) TestStrMapSortedKeys(c *C) { c.Check(StrMapSortedKeys(map[string]string{}), DeepEquals, []string{}) c.Check(StrMapSortedKeys(map[string]string{"x": "1", "a": "3", "y": "4"}), DeepEquals, []string{"a", "x", "y"}) } + +func (s *ListSuite) TestStrSliceDeduplicate(c *C) { + c.Check(StrSliceDeduplicate([]string{}), DeepEquals, []string{}) + c.Check(StrSliceDeduplicate([]string{"a"}), DeepEquals, []string{"a"}) + c.Check(StrSliceDeduplicate([]string{"a", "b"}), DeepEquals, []string{"a", "b"}) + c.Check(StrSliceDeduplicate([]string{"a", "a"}), DeepEquals, []string{"a"}) + c.Check(StrSliceDeduplicate([]string{"a", "b", "c", "a", "a", "b"}), DeepEquals, []string{"a", "b", "c"}) + c.Check(StrSliceDeduplicate([]string{"a", "b", "c", "d", "e", "f"}), DeepEquals, []string{"a", "b", "c", "d", "e", "f"}) +}