Skip to content

Commit

Permalink
feat: add support for From helper method
Browse files Browse the repository at this point in the history
  • Loading branch information
TristanSpeakEasy committed Aug 13, 2024
1 parent 86d7572 commit 2f16293
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,26 @@ for k := range om.KeysNewest() {
// 1
```

`From` is a convenience function that creates a new `OrderedMap` from an iterator over key-value pairs.

```go
om := orderedmap.New[int, string]()
om.Set(1, "foo")
om.Set(2, "bar")
om.Set(3, "baz")

om2 := orderedmap.From(om.FromOldest())

for k, v := range om2.FromOldest() {
fmt.Printf("%d => %s\n", k, v)
}

// prints:
// 1 => foo
// 2 => bar
// 3 => baz
```

## Alternatives

There are several other ordered map golang implementations out there, but I believe that at the time of writing none of them offer the same functionality as this library; more specifically:
Expand Down
11 changes: 11 additions & 0 deletions orderedmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,14 @@ func (om *OrderedMap[K, V]) ValuesFromNewest() iter.Seq[V] {
}
}
}

// From creates a new OrderedMap from an iterator over key-value pairs.
func From[K comparable, V any](i iter.Seq2[K, V]) *OrderedMap[K, V] {
om := New[K, V]()

for k, v := range i {
om.Set(k, v)
}

return om
}
44 changes: 44 additions & 0 deletions orderedmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -452,3 +452,47 @@ func TestIterators(t *testing.T) {

assert.Equal(t, expectedValuesFromNewest, values)
}

func TestIteratorsFrom(t *testing.T) {
om := New[int, any]()
om.Set(1, "bar")
om.Set(2, 28)
om.Set(3, 100)
om.Set(4, "baz")
om.Set(5, "28")
om.Set(6, "100")
om.Set(7, "baz")
om.Set(8, "baz")

om2 := From(om.FromOldest())

expectedKeys := []int{1, 2, 3, 4, 5, 6, 7, 8}
expectedValues := []any{"bar", 28, 100, "baz", "28", "100", "baz", "baz"}

var keys []int
var values []any

for k, v := range om2.FromOldest() {
keys = append(keys, k)
values = append(values, v)
}

assert.Equal(t, expectedKeys, keys)
assert.Equal(t, expectedValues, values)

expectedKeysFromNewest := []int{8, 7, 6, 5, 4, 3, 2, 1}
expectedValuesFromNewest := []any{"baz", "baz", "100", "28", "baz", 100, 28, "bar"}

om2 = From(om.FromNewest())

keys = []int{}
values = []any{}

for k, v := range om2.FromOldest() {
keys = append(keys, k)
values = append(values, v)
}

assert.Equal(t, expectedKeysFromNewest, keys)
assert.Equal(t, expectedValuesFromNewest, values)
}

0 comments on commit 2f16293

Please sign in to comment.