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
9 changes: 9 additions & 0 deletions lib/fromarray.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
32 changes: 32 additions & 0 deletions test/fromarray_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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