diff --git a/lib/sorted_containers/sorted_array.rb b/lib/sorted_containers/sorted_array.rb index e2abefb..5e32882 100644 --- a/lib/sorted_containers/sorted_array.rb +++ b/lib/sorted_containers/sorted_array.rb @@ -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. diff --git a/spec/sorted_array_spec.rb b/spec/sorted_array_spec.rb index 0505f8a..39faf83 100644 --- a/spec/sorted_array_spec.rb +++ b/spec/sorted_array_spec.rb @@ -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