Skip to content

Commit

Permalink
Add a convenience Of builder function to mapset (#22)
Browse files Browse the repository at this point in the history
Also update README to include doc for `Of`
  • Loading branch information
shawc71 authored Jul 11, 2022
1 parent 47c10d2 commit ae83fa5
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
9 changes: 9 additions & 0 deletions mapset/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ false

- [type Set](<#type-set>)
- [func New[K comparable]() Set[K]](<#func-new>)
- [func Of[K comparable](vals ...K) Set[K]](<#func-of>)
- [func (s Set[K]) Each(fn func(key K))](<#func-setk-each>)
- [func (s Set[K]) Has(val K) bool](<#func-setk-has>)
- [func (s Set[K]) Put(val K)](<#func-setk-put>)
Expand All @@ -69,6 +70,14 @@ func New[K comparable]() Set[K]

New returns an empty hashset\.

### func [Of](<https://github.com/zyedidia/generic/blob/master/mapset/set.go#L17>)

```go
func Of[K comparable](vals ...K) Set[K]]
```

Returns a new hashset initialized with the given values\.

### func \(Set\[K\]\) [Each](<https://github.com/zyedidia/generic/blob/master/mapset/set.go#L38>)

```go
Expand Down
9 changes: 9 additions & 0 deletions mapset/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ func New[K comparable]() Set[K] {
}
}

// Of returns a new hashset initialized with the given 'vals'
func Of[K comparable](vals ...K) Set[K] {
s := New[K]()
for _, val := range vals {
s.Put(val)
}
return s
}

// Put adds 'val' to the set.
func (s Set[K]) Put(val K) {
s.m[val] = struct{}{}
Expand Down
24 changes: 24 additions & 0 deletions mapset/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,30 @@ func TestCrossCheck(t *testing.T) {
}
}

func TestOf(t *testing.T) {
testcases := []struct {
name string
input []string
}{
{"init with several items", []string{"foo", "bar", "baz"}},
{"init without values", []string{}},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
set := mapset.Of[string](tc.input...)

if len(tc.input) != set.Size() {
t.Fatalf("expected %d elements in set, got %d", len(tc.input), set.Size())
}
for _, val := range tc.input {
if !set.Has(val) {
t.Fatalf("expected to find val '%s' in set but did not", val)
}
}
})
}
}

func Example() {
set := mapset.New[string]()
set.Put("foo")
Expand Down

0 comments on commit ae83fa5

Please sign in to comment.