commit 1626fb35db7af5d3db770f95b3b9429f0ac198f6 Author: Knut Ahlers Date: Sat Apr 16 01:13:39 2016 +0200 Added some helpers diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..73d38b1 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: go + +go: + - 1.5 + - 1.6 + - tip diff --git a/go_helpers_suite_test.go b/go_helpers_suite_test.go new file mode 100644 index 0000000..ed36a97 --- /dev/null +++ b/go_helpers_suite_test.go @@ -0,0 +1,13 @@ +package helpers_test + +import ( + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" + + "testing" +) + +func TestGoHelpers(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "GoHelpers Suite") +} diff --git a/slice.go b/slice.go new file mode 100644 index 0000000..292f91b --- /dev/null +++ b/slice.go @@ -0,0 +1,21 @@ +package helpers + +// AppendIfMissing adds a string to a slice when it's not present yet +func AppendIfMissing(slice []string, s string) []string { + for _, e := range slice { + if e == s { + return slice + } + } + return append(slice, s) +} + +// StringInSlice checks for the existence of a string in the slice +func StringInSlice(a string, list []string) bool { + for _, b := range list { + if b == a { + return true + } + } + return false +} diff --git a/slice_test.go b/slice_test.go new file mode 100644 index 0000000..fa51118 --- /dev/null +++ b/slice_test.go @@ -0,0 +1,52 @@ +package helpers_test + +import ( + . "github.com/Luzifer/go_helpers" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +var _ = Describe("Slice", func() { + + Context("AppendIfMissing", func() { + var sl = []string{ + "test1", + "test2", + "test3", + } + + It("should not append existing elements", func() { + Expect(len(AppendIfMissing(sl, "test1"))).To(Equal(3)) + Expect(len(AppendIfMissing(sl, "test2"))).To(Equal(3)) + Expect(len(AppendIfMissing(sl, "test3"))).To(Equal(3)) + }) + + It("should append not existing elements", func() { + Expect(len(AppendIfMissing(sl, "test4"))).To(Equal(4)) + Expect(len(AppendIfMissing(sl, "test5"))).To(Equal(4)) + Expect(len(AppendIfMissing(sl, "test6"))).To(Equal(4)) + }) + }) + + Context("StringInSlice", func() { + var sl = []string{ + "test1", + "test2", + "test3", + } + + It("should find elements of slice", func() { + Expect(StringInSlice("test1", sl)).To(Equal(true)) + Expect(StringInSlice("test2", sl)).To(Equal(true)) + Expect(StringInSlice("test3", sl)).To(Equal(true)) + }) + + It("should not find elements not in slice", func() { + Expect(StringInSlice("test4", sl)).To(Equal(false)) + Expect(StringInSlice("test5", sl)).To(Equal(false)) + Expect(StringInSlice("test6", sl)).To(Equal(false)) + }) + }) + +})