Skip to content

Commit b3f0281

Browse files
committed
Add Set implementation
1 parent f9d3c1c commit b3f0281

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

set.go

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package collections
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
)
7+
8+
// Collection that stores a set of homogenous elements.
9+
type Set[T CollectionElement] struct {
10+
items map[T]struct{}
11+
}
12+
13+
// Factory method to create an empty set with predefined capacity.
14+
func NewSet[T CollectionElement]() *Set[T] {
15+
s := &Set[T]{}
16+
s.items = make(map[T]struct{})
17+
return s
18+
}
19+
20+
// Factory method to create a set from an array.
21+
func ToSet[T CollectionElement](array []T) *Set[T] {
22+
s := &Set[T]{}
23+
s.items = make(map[T]struct{}, len(array))
24+
for _, item := range array {
25+
s.items[item] = struct{}{}
26+
}
27+
return s
28+
}
29+
30+
// Add element to set.
31+
func (s *Set[T]) Add(item T) {
32+
s.items[item] = struct{}{}
33+
}
34+
35+
// Checks whether an element is present in the set.
36+
func (s *Set[T]) Contains(item T) bool {
37+
_, ok := s.items[item]
38+
return ok
39+
}
40+
41+
// Updates the current set to be it's union with another set.
42+
func (s *Set[T]) Extend(s2 *Set[T]) {
43+
for key := range s2.items {
44+
s.items[key] = struct{}{}
45+
}
46+
}
47+
48+
// Removes all elements from the set.
49+
func (s *Set[T]) Clear() {
50+
s.items = make(map[T]struct{})
51+
}
52+
53+
// Removes occurence of the given element from the set.
54+
// Returns an error if the element is not present in the set.
55+
func (s *Set[T]) Remove(item T) error {
56+
if _, ok := s.items[item]; !ok {
57+
return ErrItemNotFound
58+
}
59+
delete(s.items, item)
60+
return nil
61+
}
62+
63+
// Returns an slice containing elements of the set.
64+
func (s *Set[T]) ToArray() []T {
65+
result := make([]T, 0, s.Size())
66+
for key := range s.items {
67+
result = append(result, key)
68+
}
69+
return result
70+
}
71+
72+
// Returns the number of elements in the set.
73+
func (s Set[T]) Size() int {
74+
return len(s.items)
75+
}
76+
77+
// Returns a string description of the set.
78+
func (s Set[T]) String() string {
79+
resultStrings := make([]string, 0, s.Size())
80+
for e := range s.items {
81+
resultStrings = append(resultStrings, fmt.Sprint(e))
82+
}
83+
84+
return "{" + strings.Join(resultStrings, ",") + "}"
85+
}
86+
87+
func (_ Set[T]) Type() CollectionType {
88+
return TypeSet
89+
}

0 commit comments

Comments
 (0)