Skip to content

Commit

Permalink
Merge pull request #11 from billryan/dev
Browse files Browse the repository at this point in the history
add Map
  • Loading branch information
billryan authored Feb 2, 2020
2 parents f892cf4 + 93755c3 commit c4258f2
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
9 changes: 9 additions & 0 deletions set/hashset.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ func (s *HashSet) Foreach(f func(interface{})) {
}
}

// Call f for each item in the set, set result as new key
func (s *HashSet) Map(f func(interface{}) interface{}) Set {
n := make(map[interface{}]nothing)
for k := range s.hash {
n[f(k)] = nothing{}
}
return &HashSet{n}
}

// Returns true if this set contains no elements.
func (s *HashSet) IsEmpty() bool {
return len(s.hash) == 0
Expand Down
16 changes: 16 additions & 0 deletions set/hashset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,22 @@ func TestSet_Foreach(t *testing.T) {
s.Foreach(f)
}

func TestHashSet_Map(t *testing.T) {
oldSet := NewHashSet(1, 2, 3)
f := func(x int) int { return x * x }
fWrapper := func(x interface{}) interface{} {
xInt := x.(int)
return f(xInt)
}
s := oldSet.Map(fWrapper)
if s.Len() != oldSet.Len() {
t.Errorf("Length should be %d", oldSet.Len())
}
if !s.ContainsAll(1, 4, 9) {
t.Error("Set should be 1, 4, 9")
}
}

func TestSet_Len(t *testing.T) {
s := NewHashSet()
if s.Len() != 0 {
Expand Down
3 changes: 3 additions & 0 deletions set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ type Set interface {
// Call f for each item in the set
Foreach(f func(interface{}))

// Map f for each item
Map(f func(interface{}) interface{}) Set

// Returns true if this set contains no elements.
IsEmpty() bool

Expand Down

0 comments on commit c4258f2

Please sign in to comment.