randmap

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2025 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package randmap implements key-value map capable of uniform sampling of keys in it.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type RandMap

type RandMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

RandMap represents key-value map which allows to fetch random key from map, granting equal probability of selection among keys. Time complexity of all operations is O(1) am.

func Make

func Make[K comparable, V any]() *RandMap[K, V]

Make creates empty map.

func Wrap

func Wrap[K comparable, V any](m map[K]V) *RandMap[K, V]

Wrap indexes and wraps existing standard map into a *RandMap instance. Original map should not be modified directly after that.

func (*RandMap[K, V]) Delete

func (m *RandMap[K, V]) Delete(key K)

Delete removes key from map.

func (*RandMap[K, V]) Get

func (m *RandMap[K, V]) Get(key K) (val V, ok bool)

Get retrieves key from map.

func (*RandMap[K, V]) GetRandom

func (m *RandMap[K, V]) GetRandom() (K, V, bool)

GetRandom retrieves uniformly-distributed random key-value pair from map, if it's not empty.

func (*RandMap[K, V]) Len

func (m *RandMap[K, V]) Len() int

Len returns number of key-value pairs in map.

func (*RandMap[K, V]) Range

func (m *RandMap[K, V]) Range(f func(key K, value V) bool)

Range iterates over all map elements.

Example
package main

import (
	"fmt"

	"github.com/Snawoot/secache/randmap"
)

func main() {
	m := randmap.Wrap(map[string]int{
		"a": 1,
		"b": 2,
		"c": 3,
	})
	for k, v := range m.Range {
		fmt.Println(k, v)
	}
}
Output:

a 1
b 2
c 3

func (*RandMap[K, V]) Set

func (m *RandMap[K, V]) Set(key K, item V)

Set adds or updates key-value pair in map.

Jump to

Keyboard shortcuts

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