Merge pull request #3173 from natasha41575/StringListSet

added StringList set
This commit is contained in:
Jeff Regan
2020-11-03 13:34:56 -08:00
committed by GitHub
3 changed files with 98 additions and 0 deletions

54
kyaml/sets/sets_test.go Normal file
View File

@@ -0,0 +1,54 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package sets
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestStringList_Len(t *testing.T) {
var sl0 StringList = [][]string{}
assert.Equal(t, 0, sl0.Len())
var sl1 StringList = [][]string{
{""},
}
assert.Equal(t, 1, sl1.Len())
var sl2 StringList = [][]string{
{"a", "b"},
{"b", "c"},
}
assert.Equal(t, 2, sl2.Len())
}
func TestStringList_Insert(t *testing.T) {
var sl StringList
assert.Equal(t, 0, sl.Len())
sl = sl.Insert([]string{"a", "b", "c"})
assert.Equal(t, 1, sl.Len())
sl = sl.Insert([]string{"c", "b", "a"})
assert.Equal(t, 2, sl.Len())
sl = sl.Insert([]string{"a", "b", "c"})
assert.Equal(t, 2, sl.Len())
}
func TestStringList_Has(t *testing.T) {
var sl StringList
assert.False(t, sl.Has([]string{}))
assert.False(t, sl.Has([]string{"a", "b", "c"}))
sl = sl.Insert([]string{"a", "b", "c"})
assert.True(t, sl.Has([]string{"a", "b", "c"}))
assert.False(t, sl.Has([]string{"b", "c", "a"}))
sl = sl.Insert([]string{})
assert.True(t, sl.Has([]string{}))
}

44
kyaml/sets/stringlist.go Normal file
View File

@@ -0,0 +1,44 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package sets
// StringList is a set, where each element of
// the set is a string slice.
type StringList [][]string
func (s StringList) Len() int {
return len(s)
}
func (s StringList) Insert(val []string) StringList {
if !s.Has(val) {
return append(s, val)
}
return s
}
func (s StringList) Has(val []string) bool {
if len(s) == 0 {
return false
}
for i := range s {
if isStringSliceEqual(s[i], val) {
return true
}
}
return false
}
func isStringSliceEqual (s []string, t []string) bool {
if len(s) != len(t) {
return false
}
for i := range s {
if s[i] != t[i] {
return false
}
}
return true
}