Skip to content

Maps

Maps in Chuks are unordered collections of key-value pairs. Keys must be primitive types (strings, integers, booleans), but values can be anything — including other collections or custom types. All map methods are built-in and require no imports.

Maps are declared using the map[KeyType]ValueType syntax.

// Map from strings to integers
var scores: map[string]int = {
"Alice": 95,
"Bob": 88
};
// Map with string keys and any values
var settings: map[string]any = {
"darkMode": true,
"theme": "ocean",
"version": 2
};

Use square bracket notation with the key. If a key doesn’t exist, the returned value is null.

var score = scores["Alice"];
scores["Charlie"] = 92; // Add or update

Returns the number of key-value pairs in the map.

println(scores.length); // 2

Alias for length.

println(scores.size); // 2

Sets the value for the given key and returns the map, allowing method chaining.

var m: map[string]int = {};
m.set("a", 1).set("b", 2).set("c", 3);
println(m); // {a: 1, b: 2, c: 3}

Returns the value for the given key, or null if not found.

var m: map[string]int = {"x": 10, "y": 20};
println(m.get("x")); // 10
println(m.get("z")); // null

Returns true if the map contains the given key.

var m: map[string]int = {"x": 10};
println(m.has("x")); // true
println(m.has("z")); // false

Returns an array of all keys. Order is not guaranteed.

var names = scores.keys();
// names might be ["Alice", "Bob"] or ["Bob", "Alice"]

Returns an array of all values.

var allScores = scores.values();
// allScores might be [95, 88]

Returns an array of [key, value] pairs.

var m: map[string]int = {"x": 1, "y": 2};
var pairs: any = m.entries();
println(pairs); // [["x", 1], ["y", 2]]

Removes the key-value pair for the given key. Does nothing if the key doesn’t exist.

scores.delete("Alice");
// scores now only contains {"Bob": 88}

Removes all elements from the map.

scores.clear();
println(scores.length); // 0

Executes a callback for each key-value pair. Callback receives (value, key, map).

var m: map[string]int = {"a": 1, "b": 2, "c": 3};
m.forEach(function(val: any, key: any, mp: any): any {
println(key, "=", val);
});

Returns the key associated with the given value. Useful for reverse lookups.

var m: map[string]int = {"Alice": 95, "Bob": 88};
println(m.getName(95)); // "Alice"

Returns true if the value exists in the map.

var m: map[string]int = {"Alice": 95, "Bob": 88};
println(m.isValid(95)); // true
println(m.isValid(100)); // false

Use a for...in loop to iterate over map keys:

var scores: map[string]int = {"math": 90, "science": 85};
for (var key in scores) {
println(key + ": " + scores[key]);
}

Or use the forEach method for a functional style:

scores.forEach(function(val: any, key: any, mp: any): any {
println(key + " = " + val);
});