Skip to content

Commit fa94fe1

Browse files
committed
#33 FromArray.any_match + unit tests
1 parent 51c512b commit fa94fe1

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

lib/fromarray.rb

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@ def skip(count)
101101
# given predicate (a function which performs a test on the value and
102102
# should return a boolean).
103103
#
104-
# If the stream is empty, the returned value is true.
104+
# If the stream is empty, the returned value is true and the predicate
105+
# is not called at all.
105106
#
106107
# This is a terminal operation.
107108
# +test+:: A function which should perform some boolean test on the
@@ -113,6 +114,24 @@ def all_match(&test)
113114
true
114115
end
115116

117+
# Returns true if any of the elements of the Stream are matching
118+
# the given predicate (a function which performs a test on the value and
119+
# should return a boolean). Iteration will stop at the first match.
120+
#
121+
# If the stream is empty, the returned value is false and the predicate
122+
# is not called at all.
123+
#
124+
# This is a terminal operation.
125+
#
126+
# +test+:: A function which should perform some boolean test on the
127+
# given value.
128+
def any_match(&test)
129+
@array.each do |val|
130+
return true if test.call(val)
131+
end
132+
false
133+
end
134+
116135
# Collect the stream's data into an array and return it.
117136
# This is a terminal operation.
118137
def collect

test/fromarray_test.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,5 +258,33 @@ def test_not_all_elements_match
258258
'Expected false because not all elements are a match!'
259259
)
260260
end
261+
262+
# FromArray.any_match returns true if one element matches.
263+
def test_any_element_matches
264+
stream = FromArray.new([2, 4, 6, 8])
265+
assert(
266+
stream.any_match { |val| val == 4 },
267+
'Stream contains element 4, it should match!'
268+
)
269+
end
270+
271+
# FromArray.any_match returns true if all elements match.
272+
def test_any_match_all
273+
stream = FromArray.new([2, 4, 6, 8])
274+
assert(
275+
stream.any_match { |val| val %2 == 0 },
276+
'All elements are even, it should match!'
277+
)
278+
end
279+
280+
# FromArray.any_match returns false and the predicate is never called,
281+
# because the stream is empty.
282+
def test_any_match_empty
283+
stream = FromArray.new([])
284+
assert(
285+
!stream.any_match { raise ScriptError, 'Should not be called' },
286+
'Stream is empty, any_match should be false!'
287+
)
288+
end
261289
end
262290
end

0 commit comments

Comments
 (0)