Skip to content

Commit

Permalink
Merge pull request kubernetes#4422 from derekwaynecarr/set_difference
Browse files Browse the repository at this point in the history
Set should have a difference function
  • Loading branch information
thockin committed Feb 13, 2015
2 parents 3001a1d + e7a0340 commit 063ff66
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pkg/util/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,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") {
t.Errorf("Unexpected contents: %#v", d.List())
}
}

0 comments on commit 063ff66

Please sign in to comment.