Commit 6f1343bd authored by Phillip Couto's avatar Phillip Couto 🔨

Added strings set to package

parent 21f708e7
Pipeline #6608 passed with stage
in 30 seconds
image: golang
cache:
paths:
- go/
variables:
GOPATH: "$CI_PROJECT_DIR/go"
GOCACHE: "$CI_PROJECT_DIR/go/cache"
GOPROXY: "https://proxy.golang.org"
test:
script:
- go test --cover ./...
\ No newline at end of file
// Common is a collection of common packages that are shared between projects.
//
// This allows for cleaner code usage within Eckler and also reduces dependency
// bloat when using external dependencies.
package common
package sets
//Strings represents a set of strings
type Strings struct {
data map[string]bool
}
//NewStrings initializes a new set of strings
func NewStrings(initialValues ...string) *Strings {
data := make(map[string]bool)
for _, v := range initialValues {
data[v] = true
}
return &Strings{
data: data,
}
}
//Add will add one or more values to the set
func (ss *Strings) Add(values ...string) {
for _, v := range values {
ss.data[v] = true
}
}
//Cardinality will return the number of unique elements in the set
func (ss *Strings) Cardinality() int {
return len(ss.data)
}
//Contains will determine if the string provided exists in the set
func (ss *Strings) Contains(value string) bool {
v, ok := ss.data[value]
return ok && v
}
//Intersect will return a new set with only the values found in both sets
func (ss *Strings) Intersect(ss2 *Strings) *Strings {
src, dest := ss, ss2
if len(ss.data) > len(ss2.data) {
src, dest = ss2, ss
}
results := make(map[string]bool)
for v := range src.data {
if dest.Contains(v) {
results[v] = true
}
}
return &Strings{
data: results,
}
}
package sets
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestStrings(t *testing.T) {
s := NewStrings()
s.Add("A")
s.Add("B")
require.Equal(t, 2, s.Cardinality())
require.True(t, s.Contains("B"))
require.False(t, s.Contains("C"))
s2 := NewStrings()
s2.Add("B")
s2.Add("C")
s3 := s.Intersect(s2)
require.Equal(t, 1, s3.Cardinality())
require.True(t, s3.Contains("B"))
require.False(t, s3.Contains("A"))
require.False(t, s3.Contains("C"))
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment