Skip to content

Commit 06b3cab

Browse files
authored
Merge pull request moonbitlang#434 from ZnPdCo/map-as-iter
add Map::as_iter method
2 parents 58d5e0a + 33c8f56 commit 06b3cab

4 files changed

Lines changed: 39 additions & 1 deletion

File tree

map/map.mbti

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package moonbitlang/core/map
22

3+
alias @moonbitlang/core/iter as @iter
4+
35
// Values
46
fn empty[K, V]() -> Map[K, V]
57

@@ -8,6 +10,7 @@ fn singleton[K, V](K, V) -> Map[K, V]
810
// Types and methods
911
type Map
1012
impl Map {
13+
as_iter[K, V](Self[K, V]) -> @iter.Iter[Tuple[K, V]]
1114
debug_write[K : Debug, V : Debug](Self[K, V], Buffer) -> Unit
1215
filter[K : Compare + Eq, V](Self[K, V], (V) -> Bool) -> Self[K, V]
1316
filter_with_key[K : Compare + Eq, V](Self[K, V], (K, V) -> Bool) -> Self[K, V]

map/map_test.mbt

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,3 +297,23 @@ test "debug_write" {
297297
"Map::[(0, \"zero\"), (1, \"one\"), (2, \"two\"), (3, \"three\"), (8, \"eight\")]",
298298
)?
299299
}
300+
301+
test "as_iter" {
302+
let buf = Buffer::make(20)
303+
let map = Map::[(1, "one"), (2, "two"), (3, "three")]
304+
map.as_iter().iter(
305+
fn(e) {
306+
let (k, v) = e
307+
buf.write_string("[\(k)-\(v)]")
308+
},
309+
)
310+
inspect(buf, content="[1-one][2-two][3-three]")?
311+
buf.reset()
312+
map.as_iter().take(2).iter(
313+
fn(e) {
314+
let (k, v) = e
315+
buf.write_string("[\(k)-\(v)]")
316+
},
317+
)
318+
inspect(buf, content="[1-one][2-two]")?
319+
}

map/moon.pkg.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"moonbitlang/core/builtin",
44
"moonbitlang/core/assertion",
55
"moonbitlang/core/tuple",
6-
6+
"moonbitlang/core/iter",
77
"moonbitlang/core/string",
88
"moonbitlang/core/array",
99
"moonbitlang/core/coverage"

map/utils.mbt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,3 +208,18 @@ pub fn Map::from_array[K : Compare, V](array : Array[(K, V)]) -> Map[K, V] {
208208
mp
209209
}
210210
}
211+
212+
pub fn as_iter[K, V](self : Map[K, V]) -> @iter.Iter[(K, V)] {
213+
@iter.Iter::_unstable_internal_make(
214+
fn(yield) {
215+
let arr = self.to_array()
216+
for i = 0, len = arr.length(); i < len; i = i + 1 {
217+
match arr[i] {
218+
(key, value) => if yield((key, value)).not() { break false }
219+
}
220+
} else {
221+
true
222+
}
223+
},
224+
)
225+
}

0 commit comments

Comments
 (0)