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
17 changes: 17 additions & 0 deletions lib/fromarray.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,23 @@ def filter(&condition)
FromArray.new(filtered)
end

# Map the stream's elements to a given value using a function.
# Example (map int to string):
#
# stream = Stream::FromArray.new([1, 2, 3])
# collected = stream.map {|num| num.to_s}.collect
# puts collected # ['1', '2', '3']
#
# +function+:: Ruby Block function taking one parameter
# (the element in the stream).
def map(&function)
mapped = []
@array.each do |val|
mapped.push(function.call(val))
end
FromArray.new(mapped)
end

# Skip the first n elements of the stream.
# +count+:: Number of elements to skip from the beginning of the stream.
def skip(count)
Expand Down
31 changes: 28 additions & 3 deletions test/fromarray_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def test_skips_all_elements_count_gt_size
# condition.
def test_filter_elements
stream = FromArray.new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
collected = stream.filter {|num| num % 2 == 0}.collect
collected = stream.filter { |num| num % 2 == 0 }.collect
collected.each do |val|
assert(val.even?)
end
Expand All @@ -138,15 +138,15 @@ def test_filter_elements
# the condition.
def test_filters_no_elements
stream = FromArray.new([2, 4, 6, 8])
collected = stream.filter {|num| num % 2 == 0}.collect
collected = stream.filter { |num| num % 2 == 0 }.collect
assert(stream.collect == collected)
end

# FromArray filters out all elements because none of are satisfying
# the condition.
def test_filters_all_elements
stream = FromArray.new([2, 4, 6, 8])
assert(stream.filter {|num| num % 2 != 0}.count == 0)
assert(stream.filter { |num| num % 2 != 0 }.count == 0)
end

# Filtering a stream should return a new instance rather than modifying
Expand All @@ -156,5 +156,30 @@ def test_filter_returns_new_instance
assert(!stream.filter(&:odd?).equal?(stream))
assert(stream.collect == [2, 4, 6, 8])
end

# FromArray can map its elements using a given function.
def test_map_elements
stream = FromArray.new([1, 2, 3])
strings = stream.map { |num| num.to_s }.collect
strings.each do |val|
assert(val.is_a?(String))
end
end

# FromArray can map its single element.
def test_maps_one_element
stream = FromArray.new([1])
strings = stream.map { |num| num.to_s }.collect
strings.each do |val|
assert(val.is_a?(String))
end
end

# FromArray.map works when the stream is empty.
def test_maps_no_elements
stream = FromArray.new([])
collected = stream.map { |val| val.to_s }.collect
assert(collected.empty?)
end
end
end