Skip to content

Commit

Permalink
add at method to SortedArray
Browse files Browse the repository at this point in the history
  • Loading branch information
GarrisonJ committed Apr 29, 2024
1 parent 91b9de3 commit db77350
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/sorted_containers/sorted_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,19 @@ def add(value)

# rubocop:enable Metrics/MethodLength

# Returns the element at +Integer+ offset +index+; does not modify +self+.
# If +index+ is negative, counts from the end of +self+.
# Returns +nil+ if the +index+ is out of range.
# Will raise +TypeError+ if the +index+ is not an +Integer+.
#
# @param index [Integer] The index of the value to retrieve.
# @return [Object] The value at the specified index.
def at(index)
raise TypeError, "no implicit conversion of #{index.class} into Integer" unless index.is_a?(Integer)

self[index.to_i]
end

# Returns a string representation of the sorted array.
#
# @return [String] A string representation of the sorted array.
Expand Down
22 changes: 22 additions & 0 deletions spec/sorted_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,28 @@
end
end

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

it "should handle negative indices" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.at(-1)).to eq(5)
end

it "should return nil if negative index is out of range" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.at(-6)).to be_nil
end

it "should raise exception when index is a range" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect { array.at(1..3) }.to raise_error(TypeError)
end
end

describe "load_factor" do
it "should set the load factor to the provided value" do
array = SortedContainers::SortedArray.new([], load_factor: 100)
Expand Down

0 comments on commit db77350

Please sign in to comment.