Skip to content

Commit 51c512b

Browse files
committed
#33 FromArray.all_match + unit tests
1 parent 8fdd7d4 commit 51c512b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

lib/fromarray.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ module Stream
2626
# A stream implemented based on an Array.
2727
# This class is immutable and thread-safe.
2828
# Author:: Mihai Andronache ([email protected])
29+
# Since:: 0.0.1
2930
class FromArray
3031
def initialize(array)
3132
@array = array
@@ -96,6 +97,22 @@ def skip(count)
9697
FromArray.new(skipped)
9798
end
9899

100+
# Returns true if all the elements of the Stream are matching the
101+
# given predicate (a function which performs a test on the value and
102+
# should return a boolean).
103+
#
104+
# If the stream is empty, the returned value is true.
105+
#
106+
# This is a terminal operation.
107+
# +test+:: A function which should perform some boolean test on the
108+
# given value.
109+
def all_match(&test)
110+
@array.each do |val|
111+
return false unless test.call(val)
112+
end
113+
true
114+
end
115+
99116
# Collect the stream's data into an array and return it.
100117
# This is a terminal operation.
101118
def collect

test/fromarray_test.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,5 +229,34 @@ def test_distinct_one_duplicate_element
229229
assert(collected.length == 1)
230230
assert(collected == collected.uniq)
231231
end
232+
233+
# FromArray.all_match returns true when all
234+
# elements are a match.
235+
def test_all_elements_match
236+
stream = FromArray.new([2, 4, 6, 8])
237+
assert(
238+
stream.all_match { |val| val % 2 == 0 },
239+
'All of the stream\'s elements should be even!'
240+
)
241+
end
242+
243+
# FromArray.all_match should return true if the stream is empty.
244+
def test_all_match_no_elements
245+
stream = FromArray.new([])
246+
assert(
247+
stream.all_match { |val| val % 2 == 1 },
248+
'Expected true because the stream is empty!'
249+
)
250+
end
251+
252+
# FromArray.all_match returns false because not all the
253+
# elements are a match
254+
def test_not_all_elements_match
255+
stream = FromArray.new([2, 4, 5, 6, 8])
256+
assert(
257+
stream.all_match { |val| val % 2 == 0 } == false,
258+
'Expected false because not all elements are a match!'
259+
)
260+
end
232261
end
233262
end

0 commit comments

Comments
 (0)