diff --git a/CHANGELOG.md b/CHANGELOG.md index 074a24e..aa2abe2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [0.0.9] - 2026-02-01 + +- ✨ Add Set method to Metas type + ## [0.0.8] - 2026-02-01 - ✨ Add Get method to Metas type diff --git a/models/meta_test.go b/models/meta_test.go index 6fa6141..29e32a1 100644 --- a/models/meta_test.go +++ b/models/meta_test.go @@ -142,6 +142,66 @@ func TestMetasAppendTo(t *testing.T) { assert.Equal(t, Meta{"foo", 42}, (*ms)[0]) } +func TestMetasSet(t *testing.T) { + tests := []struct { + name string + initial Metas + key string + value any + expected Metas + }{ + { + name: "Set new key", + initial: Metas{}, + key: "foo", + value: 42, + expected: Metas{{"foo", 42}}, + }, + { + name: "Update existing key", + initial: Metas{{"foo", 1}}, + key: "foo", + value: 42, + expected: Metas{{"foo", 42}}, + }, + { + name: "Update existing key with different type", + initial: Metas{{"foo", "hello"}}, + key: "foo", + value: 42, + expected: Metas{{"foo", 42}}, + }, + { + name: "Set multiple new keys", + initial: Metas{}, + key: "bar", + value: true, + expected: Metas{{"bar", true}}, + }, + { + name: "Update one of multiple existing keys", + initial: Metas{{"foo", 1}, {"bar", "hello"}}, + key: "foo", + value: 42, + expected: Metas{{"foo", 42}, {"bar", "hello"}}, + }, + { + name: "Set new key when others exist", + initial: Metas{{"foo", 1}, {"bar", "hello"}}, + key: "baz", + value: false, + expected: Metas{{"foo", 1}, {"bar", "hello"}, {"baz", false}}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := tt.initial.Set(tt.key, tt.value) + assert.ElementsMatch(t, tt.expected, result) + }) + } +} + func TestMetasGet(t *testing.T) { ms := Metas{{"foo", 42}, {"bar", "hello"}} diff --git a/models/metas.go b/models/metas.go index 9ed7006..cf4c23e 100644 --- a/models/metas.go +++ b/models/metas.go @@ -72,10 +72,28 @@ func (ms *Metas) AppendTo(k string, v any) { // Returns the value of the Meta with the given key, and a bool indicating if it was found func (ms Metas) Get(key string) (any, bool) { - for _, m := range ms { + _, m, ok := ms.findVal(key) + return m.Value, ok +} + +// Set sets the key to the given value. +// If key is already in the ms, Set updates the value of the found Meta. +// If key is not in ms, then we append a new Meta and return the modified Metas. +func (ms Metas) Set(key string, value any) Metas { + idx, m, found := ms.findVal(key) + if !found { + return ms.Append(key, value) + } + m.Value = value + ms[idx] = m + return ms +} + +func (ms Metas) findVal(key string) (idx int, m Meta, found bool) { + for idx, m = range ms { if m.Key == key { - return m.Value, true + return idx, m, true } } - return nil, false + return 0, Meta{}, false }