From 95d8815b9afab2b6306328ebb5035fd4d0ab376b Mon Sep 17 00:00:00 2001 From: amihaiemil Date: Fri, 1 May 2020 15:17:21 +0300 Subject: [PATCH] #23 FromArray.map implemented and tested --- lib/fromarray.rb | 17 +++++++++++++++++ test/fromarray_test.rb | 31 ++++++++++++++++++++++++++++--- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/lib/fromarray.rb b/lib/fromarray.rb index c407cc2..5bd4463 100644 --- a/lib/fromarray.rb +++ b/lib/fromarray.rb @@ -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) diff --git a/test/fromarray_test.rb b/test/fromarray_test.rb index 59e3ce8..7441f34 100644 --- a/test/fromarray_test.rb +++ b/test/fromarray_test.rb @@ -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 @@ -138,7 +138,7 @@ 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 @@ -146,7 +146,7 @@ def test_filters_no_elements # 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 @@ -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