orderedMap

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2023 License: MIT Imports: 6 Imported by: 0

README

Go Reference

Functional Ordered Map

There are probably better implementations of an ordered map. This one is very simple, based on a slice of functional.Pairs to store the items in order. This order will be in order that items were added or if a comparing function is supplied, in sorted order. It is not safe for concurrent use any more than the standard map type.

Get it

go get -u github.com/flowonyx/functional/orderedMap

Use it

import "github.com/flowonyx/functional/orderedMap"

Type

There is single generic type in this package: OrderedMap[KeyType, ValueType]. It has no public members and is meant to be interacted with from the functions in this package.

Functions

  • NewOrderedMap creates a new OrderedMap. If a function for comparing key:value pairs is provided, it is used to keep the items in sorted order rather than added order.
  • FromSlice creates an OrderedMap from a slice of key:value functional.Pairs. If a function for comparing key:value pairs is provided, the items are sorted.
    • If a key is repeated, the last value for the key is used.
  • ToSlice exports the map as a slice of key:value functional.Pairs.
  • Len returns the length of the map.
  • Equal tests whether two OrderedMaps are equal. Equality is based on the keys and values all being the same. Order is not considered.
  • EqualBy tests whether two OrderedMaps are equal by applying a predicate function to each value in both maps.
  • Contains tests whether the given key is present in the map.
  • Exists tests whether a key:value pair that matches the predicate is present in the map.
  • Set either adds the key and value to the map or updates the value of the key that is already present.
  • Get either gets the value associated with the key or returns the zero value of the value type if the key is not present.
  • Remove removes a key from the map.
  • TryGet returns an option.Optional value where if the key exists, it will be Some(value), otherwise it will be None.
  • Filter returns a new OrderedMap with only the values that match a predicate function.
  • Find is the same as Get except that it returns an error if the key is not found.
  • FindKey returns a key that matches a predicate function or a KeyNotFoundErr error.
  • TryFindKey is the same as FindKey but it returns an option.Option with None if no key matches instead of returning an error.
  • ForAll tests whether all key:value pairs match the predicate.
  • IsEmpty tests whether the map is empty.
  • Iter applies the action to each key:value pair in the map.
  • Iteri applies the action to each key:value pair in the map, with the index as the first parameter to the action.
  • Keys returns all the keys in the map.
  • Values returns all the values in the map.
  • Partition returns two OrderedMaps where the first contains all key:value pairs that match the predicate and the second contains all key:value pairs that do not match the predicate.
  • Fold applies a folder function to each key:value pair until arriving at the final state.
  • FoldBack applies a folder function in reverse order to each key:value pair until arriving at the final state.
  • MapTo creates a new map with the keys and values changed through a projection function.
  • MapValuesTo creates a new map with the same keys, but the values are changed through a projection function.
  • Pick searches the map looking for the first element where the given function returns a option.Some value. Returns a KeyNotFoundErr if no such element exists.
  • TryPick searches the map looking for the first element where the given function returns a option.Some value and returns the option.Some value. Returns option.None if no such element exists.
  • Set returns a copy of a map with the given key set to the given value.
  • Remove returns a copy of a map with the given key removed.

Documentation

Overview

Package orderedMap offers a map-like type that keeps it's items in either the order they are added or in sorted order if it is provided a less function at creation.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Equal

func Equal[Key, T comparable](m, m2 OrderedMap[Key, T]) bool

Equal tests whether two OrderedMaps are equal. Equality is based on the keys and values all being the same. Order is not considered.

Example
m := NewOrderedMap[int, string]()
m.Set(2, "two")
m.Set(1, "one")
m2 := NewOrderedMap[int, string]()
m2.Set(1, "one")
m2.Set(2, "two")
m3 := NewOrderedMap[int, string]()
m3.Set(1, "one")
m3.Set(2, "two")
m3.Set(3, "three")
m4 := NewOrderedMap[int, string]()
m4.Set(1, "One")
m4.Set(2, "Two")
fmt.Println(Equal(m, m2), Equal(m, m3), Equal(m, m4))
Output:

true false false

func EqualBy

func EqualBy[Key comparable, T any](predicate func(T, T) bool, m, m2 OrderedMap[Key, T]) bool

EqualBy tests whether two OrderedMaps are equal by applying a predicate to each value in both maps.

Example
type vt struct {
	Value string
}
m := NewOrderedMap[int, vt]()
m.Set(1, vt{Value: "one"})
m.Set(2, vt{Value: "two"})
m.Set(3, vt{Value: "three"})

m2 := NewOrderedMap[int, vt]()
m2.Set(1, vt{Value: "one"})
m2.Set(2, vt{Value: "two"})
m2.Set(3, vt{Value: "three"})

m3 := NewOrderedMap[int, vt]()
m3.Set(1, vt{Value: "One"})
m3.Set(2, vt{Value: "Two"})
m3.Set(3, vt{Value: "Three"})

pred := func(v1 vt, v2 vt) bool {
	return v1.Value == v2.Value
}

fmt.Println(EqualBy(pred, m, m2), EqualBy(pred, m, m3))
Output:

true false

func Fold

func Fold[Key comparable, T, State any](folder func(State, Key, T) State, initial State, table OrderedMap[Key, T]) State

Fold applies the folder function to each key, value pair until arriving at the final state.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

r := Fold(func(state int, key int, value string) int {
	// (((((1 * 1) + 1) * 2) +1) * 3) = 15
	return (state + 1) * key
}, 0, m)

fmt.Println(r)
Output:

15

func FoldBack

func FoldBack[Key comparable, T, State any](folder func(Key, T, State) State, table OrderedMap[Key, T], initial State) State

FoldBack applies the folder function in reverse order to each key, value pair until arriving at the final state.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

r := FoldBack(func(key int, value string, state int) int {
	// (((((1 * 3) + 1) * 2) +1) * 1) = 9
	return (state + 1) * key
}, m, 0)

fmt.Println(r)
Output:

9

func Pick

func Pick[Key comparable, T, R any](chooser func(Key, T) option.Option[R], table OrderedMap[Key, T]) (R, error)

Pick searches the map looking for the first element where the given function returns a Some value. Returns a KeyNotFoundErr if no such element exists.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

r, err := Pick(func(key int, _ string) option.Option[float64] {
	if key > 1 {
		return option.Some(float64(key))
	}
	return option.None[float64]()
}, m)

if err != nil {
	panic(err)
}

fmt.Printf("%.2f", r)
Output:

2.00

func TryPick

func TryPick[Key comparable, T, R any](chooser func(Key, T) option.Option[R], table OrderedMap[Key, T]) option.Option[R]

TryPick searches the map looking for the first element where the given function returns a Some value and returns the Some value. Returns None if no such element exists.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

r := TryPick(func(key int, _ string) option.Option[float64] {
	if key > 1 {
		return option.Some(float64(key))
	}
	return option.None[float64]()
}, m)

fmt.Println(r)
Output:

Some(2)

Types

type OrderedMap

type OrderedMap[Key comparable, T any] struct {
	// contains filtered or unexported fields
}

OrderedMap is a map-like structure which keeps items in order.

func FromSlice

func FromSlice[Key comparable, T any](s []Pair[Key, T], lessFunc ...func(Pair[Key, T], Pair[Key, T]) int) OrderedMap[Key, T]

FromSlice creates an OrderedMap from a slice of Key, Value Pairs. If lessFunc is provided, the items are sorted. If a key is repeated, the last value for the key is used.

Example
m := FromSlice([]functional.Pair[string, int]{
	functional.PairOf("one", 1),
	functional.PairOf("two", 2),
	functional.PairOf("two", 3),
})

fmt.Println(m.Keys(), m.Values())
Output:

[one two] [1 3]

func MapTo

func MapTo[Key, KeyR comparable, T, ValueR any](mapping func(Key, T) (KeyR, ValueR), table OrderedMap[Key, T]) OrderedMap[KeyR, ValueR]

MapTo creates a new map with the keys and values changed through the mapping function.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

r := MapTo(func(key int, value string) (string, int) {
	return value, key
}, m)

fmt.Println(r.Keys())
Output:

[one two three]

func MapValuesTo

func MapValuesTo[Key comparable, T, R any](mapping func(Key, T) R, table OrderedMap[Key, T]) OrderedMap[Key, R]

MapValuesTo creates a new map with the same keys, but the values are changed through the mapping function.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

r := MapValuesTo(func(key int, value string) int {
	return key + 1
}, m)

fmt.Println(r.Get(1))
Output:

2

func NewOrderedMap

func NewOrderedMap[Key comparable, T any](lessFunc ...func(Pair[Key, T], Pair[Key, T]) int) OrderedMap[Key, T]

NewOrderedMap creates a new OrderedMap. If lessFunc is provided, it is used to keep the items in sorted order. If lessFunc is not provided, the items are kept in the order in which they are added.

func Remove

func Remove[Key comparable, T any](table OrderedMap[Key, T], key Key) OrderedMap[Key, T]

Remove returns a copy of table with the key removed.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

r := Remove(m, 2)
fmt.Println(r.Keys())
Output:

[1 3]

func Set

func Set[Key comparable, T any](table OrderedMap[Key, T], key Key, value T) OrderedMap[Key, T]

Set returns a copy of table with the key set the value.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

r := Set(m, 2, "Two")
fmt.Println(r.Values())
Output:

[one Two three]

func (OrderedMap[Key, T]) Contains

func (m OrderedMap[Key, T]) Contains(key Key) bool

Contains tests whether the given key is present in the map.

func (OrderedMap[Key, T]) Exists

func (m OrderedMap[Key, T]) Exists(predicate func(Key, T) bool) bool

Exists tests whether a key, value pair that matches the predicate is present in the map.

func (OrderedMap[Key, T]) Filter

func (m OrderedMap[Key, T]) Filter(predicate func(Key, T) bool) OrderedMap[Key, T]

Filter returns a new OrderedMap with only the values that match the predicate.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "Three")

r := m.Filter(func(i int, s string) bool { return strings.HasPrefix(s, "T") })
fmt.Println(r.Keys())
Output:

[3]

func (OrderedMap[Key, T]) Find

func (m OrderedMap[Key, T]) Find(key Key) (T, error)

Find is the same as Get except that it returns an error if the key is not found.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

v, err := m.Find(1)
if err != nil {
	panic(err)
}

_, err = m.Find(3)

fmt.Println(v, errors.Is(err, errors.KeyNotFoundErr))
Output:

one true

func (OrderedMap[Key, T]) FindKey

func (m OrderedMap[Key, T]) FindKey(predicate func(Key, T) bool) (Key, error)

FindKey returns a key that matches the predicate or a KeyNotFoundErr error.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

v, err := m.FindKey(func(key int, value string) bool { return strings.HasPrefix(value, "t") })
if err != nil {
	panic(err)
}

_, err = m.FindKey(func(key int, value string) bool { return strings.HasPrefix(value, "T") })

fmt.Println(v, errors.Is(err, errors.KeyNotFoundErr))
Output:

2 true

func (OrderedMap[Key, T]) ForAll

func (m OrderedMap[Key, T]) ForAll(predicate func(Key, T) bool) bool

ForAll tests whether all key, value pairs match the predicate.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

lessThan3 := func(key int, _ string) bool { return key < 3 }

r1 := m.ForAll(lessThan3)
m.Set(3, "three")
r2 := m.ForAll(lessThan3)
fmt.Println(r1, r2)
Output:

true false

func (OrderedMap[Key, T]) Get

func (m OrderedMap[Key, T]) Get(key Key) T

Get either gets the value associated with the key or returns the zero value of the value type if the key is not present.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

fmt.Println(m.Get(1))
Output:

one

func (OrderedMap[Key, T]) IsEmpty

func (m OrderedMap[Key, T]) IsEmpty() bool

IsEmpty tests whether the map is empty.

func (OrderedMap[Key, T]) Iter

func (m OrderedMap[Key, T]) Iter(action func(Key, T))

Iter applies the action to each key, value pair in the map.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

m.Iter(func(key int, value string) {
	fmt.Print(key, ":", value, ",")
})
Output:

1:one,2:two,

func (OrderedMap[Key, T]) Iteri

func (m OrderedMap[Key, T]) Iteri(action func(int, Key, T))

Iteri applies the action to each key, value pair in the map, with the index as the first parameter to the action.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

m.Iteri(func(i int, key int, value string) {
	fmt.Print(i, ":", key, ":", value, ",")
})
Output:

0:1:one,1:2:two,

func (OrderedMap[Key, T]) Keys

func (m OrderedMap[Key, T]) Keys() []Key

Keys returns all the keys in the map.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

fmt.Println(m.Keys())
Output:

[1 2]

func (OrderedMap[Key, T]) Len

func (m OrderedMap[Key, T]) Len() int

Len returns the length of the map.

func (OrderedMap[Key, T]) Partition

func (m OrderedMap[Key, T]) Partition(predicate func(Key, T) bool) (trueMap OrderedMap[Key, T], falseMap OrderedMap[Key, T])

Partition returns two OrderedMaps where the first contains all key, value pairs that match the predicate and the second contains all key, value pairs that do not match the predicate.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")
m.Set(3, "three")

t, f := m.Partition(func(i int, _ string) bool {
	return i < 3
})

fmt.Println(t.Contains(3), f.Contains(3))
Output:

false true

func (*OrderedMap[Key, T]) Remove

func (m *OrderedMap[Key, T]) Remove(key Key)

Remove removes a key from the map.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

m.Remove(1)

fmt.Println(m.TryGet(1))
Output:

None

func (*OrderedMap[Key, T]) Set

func (m *OrderedMap[Key, T]) Set(key Key, value T)

Set either adds the key and value to the map or updates the value of the key that is already present.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(1, "one")
m.Set(2, "two")
fmt.Println(m.Keys(), m.Values())
Output:

[1 2] [one two]

func (OrderedMap[Key, T]) ToSlice

func (m OrderedMap[Key, T]) ToSlice() []Pair[Key, T]

ToSlice exports the map as a slice of Key, Value Pairs.

func (OrderedMap[Key, T]) TryFindKey

func (m OrderedMap[Key, T]) TryFindKey(predicate func(Key, T) bool) option.Option[Key]

TryFindKey is the same as FindKey but it returns an Option with None if no key matches instead of returning an error.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

v := m.TryFindKey(func(_ int, value string) bool { return strings.HasPrefix(value, "t") })
v2 := m.TryFindKey(func(_ int, value string) bool { return strings.HasPrefix(value, "T") })

fmt.Println(v, v2)
Output:

Some(2) None

func (OrderedMap[Key, T]) TryGet

func (m OrderedMap[Key, T]) TryGet(key Key) option.Option[T]

TryGet returns an optional value where if the key exists, it will be Some(value), otherwise it will be None.

func (OrderedMap[Key, T]) Values

func (m OrderedMap[Key, T]) Values() []T

Values returns all the values in the map.

Example
m := NewOrderedMap[int, string]()
m.Set(1, "one")
m.Set(2, "two")

fmt.Println(m.Values())
Output:

[one two]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL