From bf79e9746283dd48cc2881c725c82269276b2e9d Mon Sep 17 00:00:00 2001 From: Matthew Rich Date: Sat, 17 Aug 2024 18:14:54 -0700 Subject: [PATCH] add mapper package --- internal/mapper/mapper.go | 44 ++++++++++++++++++++++++++++ internal/mapper/mapper_test.go | 53 ++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 internal/mapper/mapper.go create mode 100644 internal/mapper/mapper_test.go diff --git a/internal/mapper/mapper.go b/internal/mapper/mapper.go new file mode 100644 index 0000000..525ac91 --- /dev/null +++ b/internal/mapper/mapper.go @@ -0,0 +1,44 @@ +// Copyright 2024 Matthew Rich . All rights reserved. + +package mapper + +type Store[Key comparable, Value any] map[Key]Value + +func (m Store[Key, Value]) Get(key Key) (Value, bool) { + v, ok := m[key] + return v, ok +} + +func (m Store[Key, Value]) Has(key Key) (ok bool) { + _, ok = m[key] + return +} + +func (m Store[Key, Value]) Set(key Key, value Value) { + m[key] = value +} + +type Mapper interface { + Get(key string) (any, bool) + Has(key string) (bool) + Set(key string, value any) +} + +type Getter[Key comparable, Value comparable] interface { + Get(key Key) (Value, bool) + Has(key Key) (bool) +} + +type Map[Key comparable, Value comparable] interface { + Get(key Key) (Value, bool) + Has(key Key) (bool) + Set(key Key, value Value) +} + +func New[Key comparable, Value comparable]() Store[Key, Value] { + return make(Store[Key, Value]) +} + +func NewString[Value comparable]() Store[string, Value] { + return make(Store[string, Value]) +} diff --git a/internal/mapper/mapper_test.go b/internal/mapper/mapper_test.go new file mode 100644 index 0000000..f983800 --- /dev/null +++ b/internal/mapper/mapper_test.go @@ -0,0 +1,53 @@ +// Copyright 2024 Matthew Rich . All rights reserved. + +package mapper + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestNewMapper(t *testing.T) { + testMapper := New[string, int]() + assert.NotNil(t, testMapper) +} + +func TestMapperGet(t *testing.T) { + testMapper := New[string, int]() + assert.NotNil(t, testMapper) + + testMapper["foo"] = 3 + v, exists := testMapper.Get("foo") + assert.True(t, exists) + assert.Equal(t, 3, v) +} + +func TestMapperInterface(t *testing.T) { + var testInterface Map[string, int] + testMapper := New[string, int]() + assert.NotNil(t, testMapper) + + testMapper["foo"] = 3 + testInterface = testMapper + v, exists := testInterface.Get("foo") + assert.True(t, exists) + assert.Equal(t, 3, v) +} + +func TestMapperMissing(t *testing.T) { + testMapper := New[string, int]() + assert.NotNil(t, testMapper) + + testMapper["foo"] = 3 + _, exists := testMapper.Get("bar") + assert.False(t, exists) +} + +func TestNewStringMapper(t *testing.T) { + testMapper := NewString[int]() + assert.NotNil(t, testMapper) + testMapper["bar"] = 10 + v, exists := testMapper.Get("bar") + assert.True(t, exists) + assert.Equal(t, 10, v) +}