Skip to content

Commit

Permalink
feat: add nameset package
Browse files Browse the repository at this point in the history
  • Loading branch information
1995parham committed Aug 29, 2024
1 parent c9b9832 commit 218e9db
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
41 changes: 41 additions & 0 deletions pkg/nameset/nameset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package nameset

import "iter"

type Nameset[T comparable] struct {
data map[T]bool
}

func (nm Nameset[T]) Add(i T) {
nm.data[i] = true
}

func (nm Nameset[T]) Remove(i T) {
delete(nm.data, i)
}

func (nm Nameset[T]) Filter(filter func(T) bool) iter.Seq[T] {
return func(yield func(i T) bool) {
for i := range nm.data {
if filter(i) && !yield(i) {
return
}
}
}
}

func (nm Nameset[T]) All() iter.Seq[T] {
return func(yield func(i T) bool) {
for i := range nm.data {
if !yield(i) {
return
}
}
}
}

func New[T comparable]() Nameset[T] {
return Nameset[T]{
data: make(map[T]bool),
}
}
65 changes: 65 additions & 0 deletions pkg/nameset/nameset_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package nameset_test

import (
"testing"

"github.com/snapp-incubator/argocd-complementary-operator/pkg/nameset"
)

func TestAll(t *testing.T) {
nm := nameset.New[int]()

elements := []int{10, 11, 12}

for _, i := range elements {
nm.Add(i)
}

validation := make(map[int]bool)
for i := range nm.All() {
validation[i] = true
}

if len(validation) != len(elements) {
t.Fatalf("all should iterate over all (%d) elements in the nameset", len(elements))
}
for _, i := range elements {
if !validation[i] {
t.Fatalf("all should iterate over all elements in the nameset, but it does not contain %d", i)
}
}
}

func TestFilter(t *testing.T) {
nm := nameset.New[int]()

elements := []int{10, 11, 12}
filter := func(i int) bool {
return i%2 == 0
}
elements_filtered := make([]int, 0)

for _, i := range elements {
if filter(i) {
elements_filtered = append(elements_filtered, i)
}
}

for _, i := range elements {
nm.Add(i)
}

validation := make(map[int]bool)
for i := range nm.Filter(filter) {
validation[i] = true
}

if len(validation) != len(elements_filtered) {
t.Fatalf("filter should iterate over all (%d) filtered elements in the nameset", len(elements_filtered))
}
for _, i := range elements_filtered {
if !validation[i] {
t.Fatalf("filter should iterate over all filtered elements in the nameset, but it does not contain %d", i)
}
}
}

0 comments on commit 218e9db

Please sign in to comment.