maputil

package
v1.100.1 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2024 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package maputil provides a collection of utility functions for Go maps.

The functions in this package are generic and can be used with any type of map.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Filter

func Filter[M ~map[K]V, K comparable, V any](m M, f func(K, V) bool) M

Filter returns a new map containing only the elements in the input map m for which the specified function f is true.

Example
package main

import (
	"fmt"

	"github.com/Vonage/gosrvlib/pkg/maputil"
)

func main() {
	m := map[int]string{0: "Hello", 1: "World"}

	filterFn := func(_ int, v string) bool { return v == "World" }

	s2 := maputil.Filter(m, filterFn)

	fmt.Println(s2)

}
Output:

map[1:World]

func Invert

func Invert[M ~map[K]V, K, V comparable](m M) map[V]K

Invert returns a new map where keys and values are swapped.

Example
package main

import (
	"fmt"

	"github.com/Vonage/gosrvlib/pkg/maputil"
)

func main() {
	m := map[int]int{1: 10, 2: 20}

	s2 := maputil.Invert(m)

	fmt.Println(s2)

}
Output:

map[10:1 20:2]

func Map

func Map[M ~map[K]V, K, J comparable, V, U any](m M, f func(K, V) (J, U)) map[J]U

Map returns a new map that contains each of the elements of the input map m mutated by the specified function.

Example
package main

import (
	"fmt"

	"github.com/Vonage/gosrvlib/pkg/maputil"
)

func main() {
	m := map[int]string{0: "Hello", 1: "World"}

	mapFn := func(k int, v string) (string, int) { return "_" + v, k + 1 }

	s2 := maputil.Map(m, mapFn)

	fmt.Println(s2)

}
Output:

map[_Hello:1 _World:2]

func Reduce

func Reduce[M ~map[K]V, K comparable, V, U any](m M, init U, f func(K, V, U) U) U

Reduce applies the reducing function f to each element of the input map m and returns the value of the last call to f. The first parameter of the reducing function f is initialized with init.

Example
package main

import (
	"fmt"

	"github.com/Vonage/gosrvlib/pkg/maputil"
)

func main() {
	m := map[int]int{0: 2, 1: 3, 2: 5, 3: 7, 4: 11}
	init := 97
	reduceFn := func(k, v, r int) int { return k + v + r }

	r := maputil.Reduce(m, init, reduceFn)

	fmt.Println(r)

}
Output:

135

Types

This section is empty.

Jump to

Keyboard shortcuts

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