Skip to content

Counter ​

Counter<T> counts scalar values and preserves their first-insertion order when frequencies tie.

Construction ​

Counter<T>() creates an empty counter. T must be a scalar value type: boolean, char, an integer, or a floating-point type. Heap-owned values such as string are not supported.

Methods ​

MethodSignatureReturnsDescription
add(T, i32?) => voidvoidIncrement an item by a positive count; the default is 1.
remove(T, i32?) => voidvoidDecrement an item by a positive count; missing or exhausted items are absent.
count(T) => i32i32Return the count, or 0 when absent.
mostCommon(usize) => [T, i32][][T, i32][]Return up to that many [item, count] pairs ordered by descending count and stable on ties.
total() => i32i32Return the sum of all counts.
unique() => usizeusizeReturn the number of present items.
isEmpty() => booleanbooleanReturn whether the counter is empty.
clear() => voidvoidRemove all items.

add, remove, and total abort with a runtime error if a positive i32 count cannot be represented.

Complexity ​

OperationTime Complexity
add, remove, countO(1) average
mostCommon(k)O(n log n)
total, clearO(n)
unique, isEmptyO(1)

Example ​

tyrus
import { Counter } from "tyrus:algorithm";

const counts = Counter<i32>();
counts.add(10, 2);
counts.add(20);

for (const pair of counts.mostCommon(2)) {
    print(pair[0]);  // 10, then 20
    print(pair[1]);  // 2, then 1
}