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

Add a function to create a new mapset initialized with given values #22

Merged
merged 1 commit into from
Jul 11, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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