From 6cc487e1c9a05f9839decfe0cf0ff870b39d9081 Mon Sep 17 00:00:00 2001 From: Garrison Jensen Date: Mon, 29 Apr 2024 10:38:35 -0700 Subject: [PATCH] Add & to SortedArray --- lib/sorted_containers/sorted_array.rb | 10 ++++++++++ spec/sorted_array_spec.rb | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/sorted_containers/sorted_array.rb b/lib/sorted_containers/sorted_array.rb index dd15ca2..8183404 100644 --- a/lib/sorted_containers/sorted_array.rb +++ b/lib/sorted_containers/sorted_array.rb @@ -28,6 +28,16 @@ def initialize(iterable = [], load_factor: DEFAULT_LOAD_FACTOR) update(iterable) end + # Returns a new SortedArray with the values from the union of the two arrays. + # + # @param other [SortedArray] The other array to union with. + # @return [SortedArray] The union 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 61f8a04..1c8cf74 100644 --- a/spec/sorted_array_spec.rb +++ b/spec/sorted_array_spec.rb @@ -1,6 +1,32 @@ # frozen_string_literal: true RSpec.describe SortedContainers::SortedArray do + describe "&" do + it "should return the intersection 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([3, 4, 5]) + end + + it "should return an empty array if there is no intersection" do + array1 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5]) + array2 = SortedContainers::SortedArray.new([6, 7, 8, 9, 10]) + expect((array1 & array2).to_a).to eq([]) + end + + it "should return an empty array if one of the arrays is empty" do + array1 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5]) + array2 = SortedContainers::SortedArray.new + expect((array1 & array2).to_a).to eq([]) + 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