Skip to content

Commit

Permalink
Add clear
Browse files Browse the repository at this point in the history
  • Loading branch information
yj-qin committed Mar 22, 2024
1 parent db2eab5 commit 5545a9a
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions hashmap/hashmap.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ let default_load_factor = 0.9
enum Entry[K, V] {
Empty
Valid((Int, K, V))
}
} derive(Debug)

/// A mutable hash map implements with Robin Hood hashing.
///
Expand Down Expand Up @@ -200,6 +200,14 @@ pub fn iteri[K, V](self : HashMap[K, V], f : (Int, K, V) -> Unit) -> Unit {
}
}

// Clears the map, removing all key-value pairs. Keeps the allocated space.
pub fn clear[K, V](self : HashMap[K, V]) -> Unit {
for i = 0; i < self.capacity; i = i + 1 {
self.entries[i] = Empty
}
self.size = 0
}

fn shift_back[K : Hash, V](self : HashMap[K, V], start_index : Int) -> Unit {
let mut prev = start_index
let mut curr = self.next_index(prev)
Expand Down Expand Up @@ -388,11 +396,26 @@ test "iteri" {
let m : HashMap[String, Int] = HashMap::[("a", 1), ("b", 2), ("c", 3)]
let mut sum = 0
let mut s = ""
m.iteri(fn(i, _k, v) { s += i.to_string(); sum += v })
m.iteri(
fn(i, _k, v) {
s += i.to_string()
sum += v
},
)
@assertion.assert_eq(s, "012")?
@assertion.assert_eq(sum, 6)?
}

test "clear" {
let m : HashMap[String, Int] = HashMap::[("a", 1), ("b", 2), ("c", 3)]
m.clear()
@assertion.assert_eq(m.size, 0)?
@assertion.assert_eq(m.capacity, 8)?
for i = 0; i < m.capacity; i = i + 1 {
@assertion.assert_is(m.entries[i], Empty)?
}
}

test "grow" {
let m : HashMap[String, Int] = HashMap::new(
~hasher=Some(fn(k) { k.length() }),
Expand Down

0 comments on commit 5545a9a

Please sign in to comment.