mapsutil

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2024 License: Unlicense Imports: 3 Imported by: 0

Documentation

Overview

Package mapsutil contains utilities for map handling.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func OrderedRange

func OrderedRange[K constraints.Ordered, V any, M ~map[K]V](m M, f func(k K, v V) (cont bool))

OrderedRange is like the usual Go range but sorts the keys before iterating ensuring a predictable order. If cont is false, OrderedRange stops the iteration.

Example
package main

import (
	"fmt"

	"github.com/AdguardTeam/golibs/mapsutil"
)

func main() {
	m := map[string]int{
		"b": 200,
		"a": 100,
		"c": 300,
		"d": 400,
	}

	mapsutil.OrderedRange(m, func(k string, v int) (cont bool) {
		fmt.Printf("value for %q is %d\n", k, v)

		// Do not print any values after "c".
		return k != "c"
	})

}
Output:

value for "a" is 100
value for "b" is 200
value for "c" is 300

func OrderedRangeError

func OrderedRangeError[K constraints.Ordered, V any, M ~map[K]V](
	m M,
	f func(k K, v V) (err error),
) (err error)

OrderedRangeError is like OrderedRange but uses an error to signal that the iteration must be stopped. err is the same error as the one returned from f, or nil if no errors are returned.

Example
package main

import (
	"fmt"

	"github.com/AdguardTeam/golibs/mapsutil"
)

func main() {
	checkKey := func(k string, v int) (err error) {
		if k == "x" {
			return fmt.Errorf("bad key: %q", k)
		}

		fmt.Printf("value for %q is %d\n", k, v)

		return nil
	}

	err := mapsutil.OrderedRangeError(
		map[string]int{
			"b": 200,
			"a": 100,
			"c": 300,
		},
		checkKey,
	)

	fmt.Println(err)

	err = mapsutil.OrderedRangeError(
		map[string]int{
			"x": 0,
		},
		checkKey,
	)

	fmt.Println(err)

}
Output:

value for "a" is 100
value for "b" is 200
value for "c" is 300
<nil>
bad key: "x"

Types

This section is empty.

Jump to

Keyboard shortcuts

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