Skip to content
Snippets Groups Projects
Unverified Commit 839916ae authored by Yorick Peterse's avatar Yorick Peterse
Browse files

Add Iterator.select

This method allows one to select specific values from an Iterator. This
requires some casts to work around the issue described in
https://gitlab.com/inko-lang/inko/issues/177. We will solve this as part
of the self-hosting compiler project.
parent d22e281e
No related branches found
No related tags found
No related merge requests found
Loading
Loading
@@ -266,6 +266,44 @@ trait Iterator!(T) {
False
}
 
# Returns an `Iterator` that only produces values for which the supplied block
# returned `True`.
#
# # Examples
#
# Selecting only certain values in an `Iterator`:
#
# Array.new(10, 20, 30)
# .iter
# .select do (value) { value > 10 }
# .to_array # => Array.new(20, 30)
def select(block: do (T) -> Boolean) -> Iterator!(T) {
let mut found: ?T = Nil
# The casts to ?Object here are needed until
# https://gitlab.com/inko-lang/inko/issues/177 has been implemented.
Enumerator.new(
while: {
{ next?.and { (found as ?Object).nil? } }.while_true {
let value = next
block.call(value).if_true {
found = value
}
}
(found as ?Object).not_nil?
},
yield: {
let yield = found!
found = Nil
yield
}
)
}
# Transforms the `Iterator` into an `Array`.
#
# This method will advance the iterator to the end.
Loading
Loading
Loading
Loading
@@ -116,6 +116,29 @@ test.group('std::iterator::Iterator.map') do (g) {
}
}
 
test.group('std::iterator::Iterator.select') do (g) {
g.test('Selecting values from an empy Iterator') {
let iter = EmptyIterator.new
let vals = iter.select do (value) { value > 10 }.to_array
assert.true(vals.empty?)
}
g.test('Selecting values from an Iterator with values') {
let iter = SimpleIterator.new
let vals = iter.select do (value) { value > 10 }.to_array
assert.equal(vals, Array.new(20, 30))
}
g.test('Selecting values from an Iterator when no values match') {
let iter = SimpleIterator.new
let vals = iter.select do (value) { value > 50 }.to_array
assert.true(vals.empty?)
}
}
test.group('std::iterator::Iterator.to_array') do (g) {
g.test('Converting an Iterator to an Array') {
let iter = SimpleIterator.new
Loading
Loading
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment