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 8063672 commit 6cc487e
Show file tree
Hide file tree
Showing 2 changed files with 36 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 @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions spec/sorted_array_spec.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down

0 comments on commit 6cc487e

Please sign in to comment.