Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion lib/fromarray.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ def skip(count)
# given predicate (a function which performs a test on the value and
# should return a boolean).
#
# If the stream is empty, the returned value is true.
# If the stream is empty, the returned value is true and the predicate
# is not called at all.
#
# This is a terminal operation.
# +test+:: A function which should perform some boolean test on the
Expand All @@ -113,6 +114,24 @@ def all_match(&test)
true
end

# Returns true if any of the elements of the Stream are matching
# the given predicate (a function which performs a test on the value and
# should return a boolean). Iteration will stop at the first match.
#
# If the stream is empty, the returned value is false and the predicate
# is not called at all.
#
# This is a terminal operation.
#
# +test+:: A function which should perform some boolean test on the
# given value.
def any_match(&test)
@array.each do |val|
return true if test.call(val)
end
false
end

# Collect the stream's data into an array and return it.
# This is a terminal operation.
def collect
Expand Down
28 changes: 28 additions & 0 deletions test/fromarray_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -258,5 +258,33 @@ def test_not_all_elements_match
'Expected false because not all elements are a match!'
)
end

# FromArray.any_match returns true if one element matches.
def test_any_element_matches
stream = FromArray.new([2, 4, 6, 8])
assert(
stream.any_match { |val| val == 4 },
'Stream contains element 4, it should match!'
)
end

# FromArray.any_match returns true if all elements match.
def test_any_match_all
stream = FromArray.new([2, 4, 6, 8])
assert(
stream.any_match { |val| val %2 == 0 },
'All elements are even, it should match!'
)
end

# FromArray.any_match returns false and the predicate is never called,
# because the stream is empty.
def test_any_match_empty
stream = FromArray.new([])
assert(
!stream.any_match { raise ScriptError, 'Should not be called' },
'Stream is empty, any_match should be false!'
)
end
end
end