From cf5b98a0d410bb975ffc72c086c929b68d965ab2 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Fri, 24 May 2019 22:30:51 +0700 Subject: strings: add function to append uniq values to slice of strings The AppendUniq will append a string to slice only if the same string its not already exist. The string is compared in case insensitive manner. --- lib/strings/strings.go | 24 ++++++++++++++++++++++++ lib/strings/strings_example_test.go | 11 +++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/strings/strings.go b/lib/strings/strings.go index c78ea788..d1e11fe8 100644 --- a/lib/strings/strings.go +++ b/lib/strings/strings.go @@ -14,6 +14,30 @@ import ( "github.com/shuLhan/share/lib/ints" ) +// +// AppendUniq append case-insensitive strings to slice of input without +// duplicate. +// +func AppendUniq(in []string, vals ...string) []string { + var found bool + + for x := 0; x < len(vals); x++ { + found = false + for y := 0; y < len(in); y++ { + if vals[x] == in[y] { + found = true + break + } + } + if found { + continue + } + in = append(in, vals[x]) + } + + return in +} + // // CountMissRate given two slice of string, count number of string that is // not equal with each other, and return the miss rate as diff --git a/lib/strings/strings_example_test.go b/lib/strings/strings_example_test.go index d661232a..df2f5125 100644 --- a/lib/strings/strings_example_test.go +++ b/lib/strings/strings_example_test.go @@ -8,6 +8,17 @@ import ( "fmt" ) +func ExampleAppendUniq() { + in := []string{"a", "", "b", "c"} + vals := []string{"b", "", "C", "d"} + + in = AppendUniq(in, vals...) + + fmt.Println(in) + // Output: + // [a b c C d] +} + func ExampleCountMissRate() { src := []string{"A", "B", "C", "D"} tgt := []string{"A", "B", "C", "D"} -- cgit v1.3