Skip to content

Commit

Permalink
Add IndexedSet (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
kubakl authored Feb 28, 2024
1 parent eb125f1 commit 7650791
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 0 deletions.
42 changes: 42 additions & 0 deletions gofp/indexed_set.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package gofp

// IndexedSet works like a map but it keeps the order.
type IndexedSet[Key, Value comparable] struct {
m map[Key]Value
i []Key
}

// Add adds a new element to the set.
func (i *IndexedSet[Key, Value]) Add(k Key, v Value) {
if i.m == nil {
i.m = make(map[Key]Value)
}

if !i.Has(k) {
i.i = append(i.i, k)
}

i.m[k] = v
}

// Get returns a the value assigned to the provided key.
func (i *IndexedSet[Key, Value]) Get(k Key) (Value, bool) {
v, ok := i.m[k]
return v, ok
}

// Has verifies if an element exists in the set.
func (i *IndexedSet[Key, Value]) Has(k Key) bool {
_, ok := i.m[k]
return ok
}

// Keys returns the keys in order.
func (i *IndexedSet[Key, Value]) Keys() []Key {
return i.i
}

// Map returns the map.
func (i *IndexedSet[Key, Value]) Map() map[Key]Value {
return i.m
}
72 changes: 72 additions & 0 deletions gofp/indexed_set_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package gofp_test

import (
"testing"

"github.com/msales/gox/gofp"
"github.com/stretchr/testify/assert"
)

func TestInitializeIndexedSet(t *testing.T) {
testCases := []struct {
name string
initFunc func() gofp.IndexedSet[int, int]
}{
{
name: "Initialize with empty value",
initFunc: func() gofp.IndexedSet[int, int] {
return gofp.IndexedSet[int, int]{}
},
},
{
name: "Initialize with var",
initFunc: func() gofp.IndexedSet[int, int] {
var val gofp.IndexedSet[int, int]
return val
},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
set := tc.initFunc()

assert.NotPanics(t, func() { set.Add(1, 1) })
})
}
}

func Test_IndexedSet_Has(t *testing.T) {
var intSet gofp.IndexedSet[int, int]
intSet.Add(1, 2)
intSet.Add(2, 1)

assert.True(t, intSet.Has(1))

type simpleStruct struct {
Foo int
Bar string
}

var simpleStructSet gofp.IndexedSet[simpleStruct, int]
simpleStructSet.Add(simpleStruct{Foo: 1, Bar: "foo"}, 1)
simpleStructSet.Add(simpleStruct{Foo: 2, Bar: "baz"}, 1)

assert.True(t, simpleStructSet.Has(simpleStruct{Foo: 1, Bar: "foo"}))
}

func Test_IndexedSet_Add(t *testing.T) {
var intSet gofp.IndexedSet[int, int]
// add unique elements
intSet.Add(1, 2)

val, ok := intSet.Get(1)
assert.True(t, ok)
assert.Equal(t, 2, val)

intSet.Add(2, 3)

val, ok = intSet.Get(2)
assert.True(t, ok)
assert.Equal(t, 3, val)
}

0 comments on commit 7650791

Please sign in to comment.