string in slice, and contains substring in slice

This commit is contained in:
Michael Baird 2017-07-11 11:30:57 -05:00
parent 8c3dfff9c9
commit 9c561f4e4b
2 changed files with 48 additions and 0 deletions

View file

@ -17,6 +17,7 @@ package pilosa
import (
"errors"
"regexp"
"strings"
"github.com/pilosa/pilosa/internal"
)
@ -56,6 +57,9 @@ var (
ErrFragmentNotFound = errors.New("fragment not found")
ErrQueryRequired = errors.New("query required")
ErrTooManyWrites = errors.New("too many write commands")
ErrConfigHosts = errors.New("missing bind address in cluster hosts")
ErrConfigBroadcastPort = errors.New("missing broadcast port in internal-hosts")
)
// Regular expression to validate index and frame names.
@ -132,3 +136,23 @@ func ValidateLabel(label string) error {
}
return nil
}
// StringInSlice checks is substring a is in the slice
func StringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
// ContainsSubstring checks is substring a is contained in the slice
func ContainsSubstring(a string, list []string) bool {
for _, b := range list {
if strings.Contains(b, a) {
return true
}
}
return false
}

View file

@ -54,3 +54,27 @@ func TestValidateLabelInvalid(t *testing.T) {
}
}
}
func TestStringInSlice(t *testing.T) {
list := []string{"localhost:10101", "localhost:10102", "localhost:10103"}
substr := "localhost:10101"
if !pilosa.StringInSlice(substr, list) {
t.Fatalf("Expected substring %s in %v", substr, list)
}
substr = "10101"
if pilosa.StringInSlice(substr, list) {
t.Fatalf("Expected substring %s not in %v", substr, list)
}
}
func TestContainsSubstring(t *testing.T) {
list := []string{"localhost:10101", "localhost:10102", "localhost:10103"}
substr := "10101"
if !pilosa.ContainsSubstring(substr, list) {
t.Fatalf("Expected substring %s contained in %v", substr, list)
}
substr = "4000"
if pilosa.ContainsSubstring(substr, list) {
t.Fatalf("Expected substring %s in not contained in %v", substr, list)
}
}