From db77350144332c9d2afaf1088252e612828f7621 Mon Sep 17 00:00:00 2001 From: Garrison Jensen Date: Mon, 29 Apr 2024 16:18:00 -0700 Subject: [PATCH] add at method to SortedArray --- lib/sorted_containers/sorted_array.rb | 13 +++++++++++++ spec/sorted_array_spec.rb | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/sorted_containers/sorted_array.rb b/lib/sorted_containers/sorted_array.rb index c4ee6fd..372c061 100644 --- a/lib/sorted_containers/sorted_array.rb +++ b/lib/sorted_containers/sorted_array.rb @@ -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. diff --git a/spec/sorted_array_spec.rb b/spec/sorted_array_spec.rb index ec79d09..73c5cc4 100644 --- a/spec/sorted_array_spec.rb +++ b/spec/sorted_array_spec.rb @@ -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)