Skip to content

Commit

Permalink
Add Iter.take
Browse files Browse the repository at this point in the history
This method returns an iterator that yields the first N items.

Changelog: added
  • Loading branch information
yorickpeterse committed Nov 25, 2023
1 parent 7a967b0 commit 6c7da74
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
15 changes: 15 additions & 0 deletions std/src/std/iter.inko
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,21 @@ trait pub Iter[T] {
self.next
}
}

# Returns a new iterator that yields the first `amount` items, or fewer if
# `amount` is greater than the number of values in the iterator.
#
# # Examples
#
# [1, 2, 3].into_iter.take(2).to_array # => [1, 2]
# [1].into_iter.take(2).to_array # => [1]
fn pub move take(amount: Int) -> Stream[T] {
let mut pending = amount

Stream.new fn move {
if (pending := pending - 1) > 0 { self.next } else { Option.None }
}
}
}

# A type that can be moved into an iterator.
Expand Down
8 changes: 8 additions & 0 deletions std/test/std/test_iter.inko
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ fn pub tests(t: mut Tests) {
t.equal(([] as Array[Int]).into_iter.skip(1).to_array, [])
}

t.test('Iter.take') fn (t) {
t.equal([1, 2, 3].into_iter.take(2).to_array, [1, 2])
t.equal([1, 2, 3].into_iter.take(10).to_array, [1, 2, 3])
t.equal([1, 2, 3].into_iter.take(0).to_array, [])
t.equal([1, 2, 3].into_iter.take(-1).to_array, [])
t.equal(([] as Array[Int]).into_iter.take(2).to_array, [])
}

t.test('Peekable.peek with an empty iterator') fn (t) {
let vals: Array[Int] = []
let iter = vals.iter.peekable
Expand Down

0 comments on commit 6c7da74

Please sign in to comment.