From fa94fe162f9044e314f9f4ce638fce3e91cde0ce Mon Sep 17 00:00:00 2001 From: amihaiemil Date: Tue, 5 May 2020 20:39:58 +0300 Subject: [PATCH] #33 FromArray.any_match + unit tests --- lib/fromarray.rb | 21 ++++++++++++++++++++- test/fromarray_test.rb | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/lib/fromarray.rb b/lib/fromarray.rb index b7bce3f..5790f54 100644 --- a/lib/fromarray.rb +++ b/lib/fromarray.rb @@ -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 @@ -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 diff --git a/test/fromarray_test.rb b/test/fromarray_test.rb index 87c845f..2522e91 100644 --- a/test/fromarray_test.rb +++ b/test/fromarray_test.rb @@ -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