Skip to content

Commit

Permalink
#33 FromArray.all_match + unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
amihaiemil committed May 5, 2020
1 parent 8fdd7d4 commit 51c512b
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/fromarray.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ module Stream
# A stream implemented based on an Array.
# This class is immutable and thread-safe.
# Author:: Mihai Andronache (amihaiemil@gmail.com)
# Since:: 0.0.1
class FromArray
def initialize(array)
@array = array
Expand Down Expand Up @@ -96,6 +97,22 @@ def skip(count)
FromArray.new(skipped)
end

# Returns true if all the elements of the Stream are matching the
# 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.
#
# This is a terminal operation.
# +test+:: A function which should perform some boolean test on the
# given value.
def all_match(&test)
@array.each do |val|
return false unless test.call(val)
end
true
end

# Collect the stream's data into an array and return it.
# This is a terminal operation.
def collect
Expand Down
29 changes: 29 additions & 0 deletions test/fromarray_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -229,5 +229,34 @@ def test_distinct_one_duplicate_element
assert(collected.length == 1)
assert(collected == collected.uniq)
end

# FromArray.all_match returns true when all
# elements are a match.
def test_all_elements_match
stream = FromArray.new([2, 4, 6, 8])
assert(
stream.all_match { |val| val % 2 == 0 },
'All of the stream\'s elements should be even!'
)
end

# FromArray.all_match should return true if the stream is empty.
def test_all_match_no_elements
stream = FromArray.new([])
assert(
stream.all_match { |val| val % 2 == 1 },
'Expected true because the stream is empty!'
)
end

# FromArray.all_match returns false because not all the
# elements are a match
def test_not_all_elements_match
stream = FromArray.new([2, 4, 5, 6, 8])
assert(
stream.all_match { |val| val % 2 == 0 } == false,
'Expected false because not all elements are a match!'
)
end
end
end

0 comments on commit 51c512b

Please # to comment.