counter

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2025 License: BSD-3-Clause Imports: 4 Imported by: 0

README

counter

Go Reference

Counter for comparable objects.

Documentation

Overview

Package counter implements a Counter for comparable items.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Counter

type Counter[T comparable] struct {
	// contains filtered or unexported fields
}

A Counter keeps track of the counts of items (which must be comparable).

func FromMap added in v0.4.0

func FromMap[T comparable](m map[T]int) *Counter[T]

FromMap returns a new Counter initialized from a map.

func New

func New[T comparable](items ...T) *Counter[T]

New returns a new Counter.

func (*Counter[T]) Add

func (c *Counter[T]) Add(item T) int

Add adds an item and returns the new item count.

func (*Counter[T]) Clone

func (c *Counter[T]) Clone() *Counter[T]

Clone clones the Counter.

func (*Counter[T]) Contains

func (c *Counter[T]) Contains(item T) bool

Contains returns true if the item is in the Counter (even when the count is 0).

func (*Counter[T]) Get

func (c *Counter[T]) Get(item T) int

Get returns the count for an item.

func (*Counter[T]) Items

func (c *Counter[T]) Items() []T

Items returns a slice with items where each item is repeated according to their count. Items with negative count are ignored.

func (*Counter[T]) Iter added in v0.5.0

func (c *Counter[T]) Iter() iter.Seq2[T, int]

Iter returns an iterator over item-count pairs. It is sorted in descending order by count.

func (*Counter[T]) Len

func (c *Counter[T]) Len() int

Len returns the number of items.

func (*Counter[T]) Map

func (c *Counter[T]) Map() map[T]int

Map returns a map with items as keys and counts as values.

func (*Counter[T]) MostCommon

func (c *Counter[T]) MostCommon(n int) []ItemCount[T]

MostCommon returns n items orderd by count (descending); n <= 0: all items.

func (*Counter[T]) Remove

func (c *Counter[T]) Remove(item T) bool

Remove removes an item from the Counter.

func (*Counter[T]) String

func (c *Counter[T]) String() string

String returns a string representation of the Counter.

func (*Counter[T]) Sub

func (c *Counter[T]) Sub(item T) int

Sub subtracts an item and returns the new item count.

func (*Counter[T]) Total

func (c *Counter[T]) Total() int

Total returns the sum of the item counts.

func (*Counter[T]) Update

func (c *Counter[T]) Update(items ...T)

Update adds items to the Counter.

type ItemCount

type ItemCount[T comparable] struct {
	Item  T
	Count int
}

An ItemCount contains an item and its count.

Jump to

Keyboard shortcuts

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