Skip to content

Commit

Permalink
Merge pull request moonbitlang#448 from yj-qin/linked-hashmap-api
Browse files Browse the repository at this point in the history
Tweak LinkedHashMap
  • Loading branch information
bobzhang authored May 27, 2024
2 parents 69a4a5f + 0f5c207 commit 720de77
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 6 deletions.
5 changes: 5 additions & 0 deletions linked_hashmap/impl_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,8 @@ test "linked list" {
m.remove("four")
inspect(m.debug_linked_list(), content="end")?
}

test "to_array" {
let map = LinkedHashMap::[(1, "one"), (2, "two"), (3, "three")]
inspect(map.to_array(), content="[(1, one), (2, two), (3, three)]")?
}
1 change: 1 addition & 0 deletions linked_hashmap/linked_hashmap.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ impl LinkedHashMap {
remove[K : Hash + Eq, V](Self[K, V], K) -> Unit
set[K : Hash + Eq, V](Self[K, V], K, V) -> Unit
size[K, V](Self[K, V]) -> Int
to_array[K, V](Self[K, V]) -> Array[Tuple[K, V]]
}

// Traits
Expand Down
2 changes: 1 addition & 1 deletion linked_hashmap/moon.pkg.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"moonbitlang/core/array",
"moonbitlang/core/option"
],
"test-import": ["moonbitlang/core/string", "moonbitlang/core/assertion"]
"test-import": ["moonbitlang/core/string", "moonbitlang/core/assertion", "moonbitlang/core/tuple"]
}
21 changes: 16 additions & 5 deletions linked_hashmap/utils.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,15 @@ pub fn iteri[K, V](self : LinkedHashMap[K, V], f : (Int, K, V) -> Unit) -> Unit
}
}

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

/// Return the iterator of the hash map, provide elements in the order of insertion.
/// Returns the iterator of the hash map, provide elements in the order of insertion.
pub fn as_iter[K, V](self : LinkedHashMap[K, V]) -> @iter.Iter[(K, V)] {
@iter.Iter::_unstable_internal_make(
fn(yield) {
Expand All @@ -109,3 +107,16 @@ pub fn as_iter[K, V](self : LinkedHashMap[K, V]) -> @iter.Iter[(K, V)] {
},
)
}

/// Converts the hash map to an array.
pub fn to_array[K, V](self : LinkedHashMap[K, V]) -> Array[(K, V)] {
let arr = []
loop self.head {
Some(Valid(~key, ~value, ~next, ..)) => {
arr.push((key, value))
continue next
}
_ => break
}
arr
}

0 comments on commit 720de77

Please sign in to comment.