Skip to content

Commit

Permalink
add abbrev to SortedArray
Browse files Browse the repository at this point in the history
  • Loading branch information
GarrisonJ committed Apr 29, 2024
1 parent 462d387 commit c138041
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/sorted_containers/sorted_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,26 @@ def slice(*args)
alias [] slice
# rubocop:enable Metrics/MethodLength

# Calculates the set of unambiguous abbreviations for the strings in +self+.
#
# require 'abbrev'
# SortedArray.new(%w{ car cone }).abbrev
# #=> {"car"=>"car", "ca"=>"car", "cone"=>"cone", "con"=>"cone", "co"=>"cone"}
#
# The optional +pattern+ parameter is a pattern or a string. Only input
# strings that match the pattern or start with the string are included in the
# output hash.
#
# SortedArray.new(%w{ fast boat day }).abbrev(/^.a/)
# #=> {"fast"=>"fast", "fas"=>"fast", "fa"=>"fast", "day"=>"day", "da"=>"day"}
#
# @param pattern [Regexp, String] The pattern to match.
# @return [Hash] The set of unambiguous abbreviations.
# See also Abbrev.abbrev
def abbrev(pattern = nil)
to_a.abbrev(pattern)
end

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

describe "abbrev" do
require "abbrev"

it "should return the abbreviations of the array" do
basic_array = %w[car cone]
array = SortedContainers::SortedArray.new(basic_array)
expect(array.abbrev).to eq(basic_array.abbrev)
end

it "should only return abbreviations of strings that match the given pattern" do
basic_array = %w[fast boat day]
array = SortedContainers::SortedArray.new(basic_array)
expect(array.abbrev(/^.a/)).to eq(basic_array.abbrev(/^.a/))
end

it "should only return abbreviantions of strings that start with the given string" do
basic_array = %w[fast boat day]
array = SortedContainers::SortedArray.new(basic_array)
expect(array.abbrev("da")).to eq(basic_array.abbrev("da"))
end

it "should return an empty hash if there are no matches" do
basic_array = %w[fast boat day]
array = SortedContainers::SortedArray.new(basic_array)
expect(array.abbrev("zz")).to eq(basic_array.abbrev("zz"))
end

it "should return an empty hash if the array is empty" do
array = SortedContainers::SortedArray.new
expect(array.abbrev).to eq({})
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 c138041

Please sign in to comment.