Skip to content

Commit

Permalink
add - to SortedArray
Browse files Browse the repository at this point in the history
  • Loading branch information
GarrisonJ committed Apr 29, 2024
1 parent e4747be commit c6dbd17
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/sorted_containers/sorted_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ def +(other)
new_instance
end

# Returns a new SortedArray with the values from the difference of the two arrays.
#
# @param other [SortedArray] The other array to subtract.
# @return [SortedArray] The difference of the two arrays.
def -(other)
new_instance = self.class.new
new_instance.update(to_a - other.to_a)
new_instance
end

# rubocop:disable Metrics/MethodLength

# Adds a value to the sorted array.
Expand Down
38 changes: 38 additions & 0 deletions spec/sorted_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,44 @@
end
end

describe "-" do
it "should return the difference of two arrays" do
array1 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
array2 = SortedContainers::SortedArray.new([3, 4, 5, 6, 7])
expect((array1 - array2).to_a).to eq([1, 2])
end

it "should return an empty array if there is no difference" do
array1 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
array2 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect((array1 - array2).to_a).to eq([])
end

it "should return the difference of two arrays with duplicates" do
array1 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5, 3, 4, 5])
array2 = SortedContainers::SortedArray.new([3, 4, 5, 6, 7])
expect((array1 - array2).to_a).to eq([1, 2])
end

it "should return an empty array if the first array is empty" do
array1 = SortedContainers::SortedArray.new
array2 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect((array1 - array2).to_a).to eq([])
end

it "should return an empty array if the second array is empty" do
array1 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
array2 = SortedContainers::SortedArray.new
expect((array1 - array2).to_a).to eq([1, 2, 3, 4, 5])
end

it "should return an empty array if both arrays are empty" do
array1 = SortedContainers::SortedArray.new
array2 = SortedContainers::SortedArray.new
expect((array1 - array2).to_a).to eq([])
end
end

describe "add" do
it "sorts items after being added in an arbitrary order" do
array = SortedContainers::SortedArray.new
Expand Down

0 comments on commit c6dbd17

Please sign in to comment.