Skip to content

Commit

Permalink
Add custom min and max methods
Browse files Browse the repository at this point in the history
  • Loading branch information
GarrisonJ committed Apr 19, 2024
1 parent dcd5300 commit 736e663
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/sorted_containers/sorted_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,20 @@ def to_a
@lists.flatten
end

# Returns the maximum value in the sorted array.
#
# @return [Object] The maximum value in the array.
def max
@lists.last&.last
end

# Returns the minimum value in the sorted array.
#
# @return [Object] The minimum value in the array.
def min
@lists.first&.first
end

# Iterates over each value in the sorted array.
#
# @yield [value] Gives each value to the block.
Expand Down
20 changes: 20 additions & 0 deletions spec/sorted_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,26 @@
expect(array.bisect_right(0)).to eq(0)
end

it "should return the minimum value in the array" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.min).to eq(1)
end

it "should return the maximum value in the array" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.max).to eq(5)
end

it "should return nil for the minimum value in an empty array" do
array = SortedContainers::SortedArray.new
expect(array.min).to be_nil
end

it "should return nil for the maximum value in an empty array" do
array = SortedContainers::SortedArray.new
expect(array.max).to be_nil
end

it "should pop the last value from the array" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.pop).to eq(5)
Expand Down

0 comments on commit 736e663

Please sign in to comment.