Overview
Insertion-ordered Map and Set.
Map<K, V> maps keys to values and Set<T> keeps distinct members;
Set is a Map<T, Bool> whose values are always true. Both iterate
with for..in, and both hand their items back in insertion order.
Keys must be Int, Float, Bool, String, or a heap object
compared by identity: two class instances with equal fields are
different keys, so look an object up with the same reference that was
stored. Int and Float never mix, so set(1, ...) and
set(1.0, ...) fill two entries. Float keys compare by bit pattern,
which makes 0.0 and -0.0 different keys while every NaN is one
key. Nothing else is hashable: Array and null keys abort the
interpreter with unhashable key type.
An entry keeps the position its key was first given. Setting a key that
is already there leaves that position alone; deleting a key and setting
it again moves it to the end. Map.keys() and Map.values() line up
index by index, and each call returns a fresh array, so writes to the
map never change an array you already took.
The map owns a reference to every key and value it holds. The count
goes up on set and down when an entry is overwritten, deleted,
cleared, or when the map itself is deinitialized; keys and values need
no cleanup of their own.
One lock guards the table, so a single map or set can be shared between
threads. A read-modify-write pair such as get then set is two
separate operations, though: hold a Mutex from @std/sync around it
when threads race.
import { Map, Set } from "@std/collections";
let ore = new Map<String, Int>();
ore.set("iron", 12);
ore.set("coal", 7);
print(ore.get("iron") ?? 0);
let seen = new Set<String>();
seen.add("iron");
seen.add("iron");
print(seen.len(), seen.values().join(", "));When to use it
Reach for @std/collections when keys need lookup or members need deduplication. Map preserves insertion order for keys() and values(); Set is built on top of it with the same guarantee.
Capabilities
- Insertion-ordered Map
- Distinct-member Set
- for..in iteration
Symbols
- class Map — Insertion-ordered hash table from keys to values. Build one with
- class Set — Distinct members backed by a
Map<T, Bool>, so members follow the same