Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set should have a difference function #4422

Merged
merged 1 commit into from
Feb 13, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions pkg/util/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,22 @@ func (s StringSet) HasAll(items ...string) bool {
return true
}

// Difference returns a set of objects that are not in s2
// For example:
// s1 = {1, 2, 3}
// s2 = {1, 2, 4, 5}
// s1.Difference(s2) = {3}
// s2.Difference(s1) = {4, 5}
func (s StringSet) Difference(s2 StringSet) StringSet {
result := NewStringSet()
for key := range s {
if !s2.Has(key) {
result.Insert(key)
}
}
return result
}

// IsSuperset returns true iff s1 is a superset of s2.
func (s1 StringSet) IsSuperset(s2 StringSet) bool {
for item := range s2 {
Expand Down
19 changes: 19 additions & 0 deletions pkg/util/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,22 @@ func TestStringSetList(t *testing.T) {
t.Errorf("List gave unexpected result: %#v", s.List())
}
}

func TestStringSetDifference(t *testing.T) {
a := NewStringSet("1", "2", "3")
b := NewStringSet("1", "2", "4", "5")
c := a.Difference(b)
d := b.Difference(a)
if len(c) != 1 {
t.Errorf("Expected len=1: %d", len(c))
}
if !c.Has("3") {
t.Errorf("Unexpected contents: %#v", c.List())
}
if len(d) != 2 {
t.Errorf("Expected len=2: %d", len(d))
}
if !d.Has("4") || !d.Has("5") {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

puke - we should probably just add an AsSlice() method.

t.Errorf("Unexpected contents: %#v", d.List())
}
}