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

Add Iterator.any?

This method can be used to check if an Iterator includes a certain
value.

This method does not reuse Iterator.find as the current Ruby compiler
does not know that type parameters are instances of Object, making it
impossible to use not_nil? on a ?T type.
parent b0ccdba1
No related branches found
No related tags found
No related merge requests found
Loading
Loading
@@ -246,6 +246,26 @@ trait Iterator!(T) {
Nil
}
 
# Returns `True` if `self` contains any value for which the `block` argument
# returned `True`.
#
# This method stops iterating over the values after the first matching value.
#
# # Examples
#
# Checking if an `Iterator` contains a value:
#
# Array.new(10, 20, 30).iter.any? do (value) { value >= 20 } # => True
def any?(block: do (T) -> Boolean) -> Boolean {
each do (value) {
block.call(value).if_true {
return True
}
}
False
}
# Transforms the `Iterator` into an `Array`.
#
# This method will advance the iterator to the end.
Loading
Loading
Loading
Loading
@@ -94,6 +94,15 @@ test.group('std::iterator::Iterator.find') do (g) {
}
}
 
test.group('std::iterator::Iterator.any?') do (g) {
g.test('Checking if an Iterator includes a value') {
let iter = SimpleIterator.new
assert.true(iter.any? do (value) { value == 20 })
assert.false(iter.any? do (value) { value == 200 })
}
}
test.group('std::iterator::Iterator.map') do (g) {
g.test('Mapping the values of an Iterator to a different value') {
let iter = SimpleIterator.new.map do (val) { val * 2 }
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