Skip to content

Commit

Permalink
Add Iter.chain
Browse files Browse the repository at this point in the history
This joins two iterators without requiring memory allocations.

Changelog: added
  • Loading branch information
rjframe committed Aug 27, 2024
1 parent 988b721 commit 6ffc443
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
27 changes: 27 additions & 0 deletions std/src/std/iter.inko
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,33 @@ trait pub Iter[T] {
}
}

# Join two `Iter` objects together, one after another.
#
# # Examples
#
# ```inko
# let a = [10, 20, 30]
# let b = [40, 50, 60]
# a.iter.chain(b.iter).to_array == [10, 20, 30, 40, 50, 60] # => true
# ```
fn pub move chain[I: mut + Iter[T]](other: I) -> Stream[T] {
let mut iter_left = true

Stream.new(fn move {
if iter_left {
let item = self.next

if item.some? {
return item
} else {
iter_left = false
}
}

other.next
})
}

# Zips two `Iter` objects together, producing a new `Iter` that produces a
# tuple containing the values of both `Iter` objects.
#
Expand Down
7 changes: 7 additions & 0 deletions std/test/std/test_iter.inko
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ fn pub tests(t: mut Tests) {
t.equal(iter.next, Option.Some(ref 30))
})

t.test('Iter.chain', fn (t) {
let a = [10, 20, 30]
let b = [40, 50, 60]

t.equal(a.iter.chain(b.iter).to_array, [10, 20, 30, 40, 50, 60])
})

t.test('Iter.zip', fn (t) {
let a = [10, 20]
let b = [30, 40]
Expand Down

0 comments on commit 6ffc443

Please sign in to comment.