Skip to content

Commit

Permalink
feat: add Map::set_default
Browse files Browse the repository at this point in the history
  • Loading branch information
KKKIIO committed Jun 24, 2024
1 parent 372aa9c commit f0d721b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions builtin/builtin.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ impl Map {
op_set[K : Hash + Eq, V](Self[K, V], K, V) -> Unit
remove[K : Hash + Eq, V](Self[K, V], K) -> Unit
set[K : Hash + Eq, V](Self[K, V], K, V) -> Unit
set_default[K : Hash + Eq, V](Self[K, V], K, () -> V) -> V
size[K, V](Self[K, V]) -> Int
to_array[K, V](Self[K, V]) -> Array[Tuple[K, V]]
to_string[K : Show, V : Show](Self[K, V]) -> String
Expand Down
16 changes: 16 additions & 0 deletions builtin/linked_hash_map.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,22 @@ pub fn get_or_default[K : Hash + Eq, V](
}
}

/// Returns the value for the given key, or sets and returns a default value if the key does not exist.
pub fn set_default[K : Hash + Eq, V](
self : Map[K, V],
key : K,
default : () -> V
) -> V {
match self.get(key) {
Some(v) => v
None => {
let v = default()
self.set(key, v)
v
}
}
}

/// Check if the hash map contains a key.
pub fn contains[K : Hash + Eq, V](self : Map[K, V], key : K) -> Bool {
match self.get(key) {
Expand Down
9 changes: 9 additions & 0 deletions builtin/linked_hash_map_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,15 @@ test "get_or_default" {
@assertion.assert_eq(m.get_or_default("d", 42), 42)?
}

test "set_default" {
let m : Map[String, Array[Int]] = Map::new()
m.set_default("a", fn() { Array::new() }).push(1)
m.set_default("b", fn() { Array::new() }).push(2)
m.set_default("a", fn() { Array::new() }).push(3)
@assertion.assert_eq(m.get("a"), Some([1, 3]))?
@assertion.assert_eq(m.get("b"), Some([2]))?
}

test "op_set" {
let m : Map[String, Int] = Map::new()
m["a"] = 1
Expand Down

0 comments on commit f0d721b

Please sign in to comment.