-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go2
61 lines (51 loc) · 1.47 KB
/
set.go2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2020. The GTL Authors. All rights reserved.
// https://github.com/modern-dev/gtl
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package gtl
// Set is unordered set based on standard map
// It can contain comparable elements only
type Set[T comparable] struct {
table map[T]bool
}
// NewSet creates an empty set.
func NewSet[T comparable]() *Set[T] {
return &Set[T]{table: map[T]bool{}}
}
// Len returns the number of elements in the container.
// Complexity - O(1).
func (s *Set[T]) Len() int {
return len(s.table)
}
// IsEmpty checks if there are elements in Set.
// Complexity - O(1).
// Returns true if the set is empty, false otherwise.
func (s *Set[T]) IsEmpty() bool {
return s.Len() == 0
}
// NotEmpty checks if there are no elements in Set.
// Complexity - O(1).
// Returns true if there are elements in set, false otherwise.
func (s *Set[T]) NotEmpty() bool {
return !s.IsEmpty()
}
// Add inserts element into Set.
// Complexity - O(1).
func (s *Set[T]) Add(item T) {
s.table[item] = true
}
// Contains checks if Set contains given element.
// Complexity - O(1).
// returns true if Set includes the element, false otherwise.
func (s *Set[T]) Contains(item T) bool {
_, exists := s.table[item]
return exists
}
// Delete deletes the element from set if it contains an element
// does nothing otherwise.
// Complexity - O(1).
func (s *Set[T]) Delete(item T) {
if s.Contains(item) {
delete(s.table, item)
}
}