Skip to content

Commit

Permalink
Add a convenience Of builder function to hashset (zyedidia#23)
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 e61ed1b commit 47c10d2
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
9 changes: 9 additions & 0 deletions hashset/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ false

- [type Set](<#type-set>)
- [func New[K any](capacity uint64, equals g.EqualsFn[K], hash g.HashFn[K]) *Set[K]](<#func-new>)
- [func Of[K comparable](capacity uint64, equals g.EqualsFn[K], hash g.HashFn[K], vals ...K) *Set[K]](<#func-of>)
- [func (s *Set[K]) Copy() *Set[K]](<#func-setk-copy>)
- [func (s *Set[K]) Each(fn func(key K))](<#func-setk-each>)
- [func (s *Set[K]) Has(val K) bool](<#func-setk-has>)
Expand All @@ -71,6 +72,14 @@ func New[K any](capacity uint64, equals g.EqualsFn[K], hash g.HashFn[K]) *Set[K]

New returns an empty hashset\.

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

```go
func Of[K comparable](capacity uint64, equals g.EqualsFn[K], hash g.HashFn[K], vals ...K) *Set[K]
```

Of returns a new hashset initialized with the given values\.

### func \(\*Set\[K\]\) [Copy](<https://github.com/zyedidia/generic/blob/master/hashset/set.go#L50>)

```go
Expand Down
9 changes: 9 additions & 0 deletions hashset/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ func New[K any](capacity uint64, equals g.EqualsFn[K], hash g.HashFn[K]) *Set[K]
}
}

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

// Put adds 'val' to the set.
func (s *Set[K]) Put(val K) {
s.m.Put(val, struct{}{})
Expand Down
24 changes: 24 additions & 0 deletions hashset/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,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 := hashset.Of[string](10, g.Equals[string], g.HashString, 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 := hashset.New[string](3, g.Equals[string], g.HashString)
set.Put("foo")
Expand Down

0 comments on commit 47c10d2

Please sign in to comment.