diff --git a/lib/fromarray.rb b/lib/fromarray.rb index 0341c53..9593fbd 100644 --- a/lib/fromarray.rb +++ b/lib/fromarray.rb @@ -70,6 +70,15 @@ def map(&function) FromArray.new(mapped) end + # Remove all the duplicates from the stream. + def distinct + unique = [] + @array.each do |val| + unique.push(val) unless unique.include? val + end + FromArray.new(unique) + 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 ef9a45b..b6f63ed 100644 --- a/test/fromarray_test.rb +++ b/test/fromarray_test.rb @@ -197,5 +197,37 @@ def test_maps_no_elements collected = stream.map { |val| val.to_s }.collect assert(collected.empty?) end + + # FromArray.distinct removes all duplicates. + def test_removes_duplicates + stream = FromArray.new([2, 2, 3, 4, 1, 1, 2, 5, 4, 3, 6]) + collected = stream.distinct.collect + assert(collected == collected.uniq) + assert(collected.length == collected.uniq.length) + end + + # FromArray.distinct works when the stream is empty. + def test_empty_distinct + stream = FromArray.new([]) + collected = stream.distinct.collect + assert(collected.length.zero?) + end + + # FromArray.distinct works when there are no duplicates in the array. + def test_distinct_no_duplicates + stream = FromArray.new([1, 2, 3, 4, 5]) + collected = stream.distinct.collect + assert(collected == collected.uniq) + assert(collected.length == collected.uniq.length) + end + + # FromArray.distinct works when there is only 1 element with + # its duplicate + def test_distinct_one_duplicate_element + stream = FromArray.new([1, 1]) + collected = stream.distinct.collect + assert(collected.length == 1) + assert(collected == collected.uniq) + end end end