Created
January 26, 2025 23:39
-
-
Save 1xtr/c52b9f53c42b7b4684178d670d070147 to your computer and use it in GitHub Desktop.
Golang alternative of JavaScript Set
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package models | |
// Set is a simple set implementation using a map. | |
type Set[T comparable] map[T]struct{} | |
// NewSet creates and returns a new Set. | |
func NewSet[T comparable]() Set[T] { | |
return make(Set[T]) | |
} | |
// Add adds a value to the set. | |
func (s Set[T]) Add(val T) { | |
s[val] = struct{}{} | |
} | |
// Contains checks if the set contains a value. | |
func (s Set[T]) Contains(val T) bool { | |
_, ok := s[val] | |
return ok | |
} | |
// ToSlice returns the set's elements as a slice. | |
func (s Set[T]) ToSlice() []T { | |
keys := make([]T, 0, len(s)) | |
for k := range s { | |
keys = append(keys, k) | |
} | |
return keys | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment