Skip to content

Commit

Permalink
add compact and compact! to SortedArray
Browse files Browse the repository at this point in the history
  • Loading branch information
GarrisonJ committed May 2, 2024
1 parent ad03367 commit 9efb6e3
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/sorted_containers/sorted_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,25 @@ def combination(n, &block)
to_a.combination(n, &block)
end

# Returns a new SortedArray containing of non-nil elements.
#
# @return [SortedArray] The compacted array.
def compact
new_instance = self.class.new
new_instance.update(to_a.compact)
new_instance
end

# Removes nil elements from the SortedArray.
#
# @return [SortedArray] The compacted array.
def compact!
values = to_a.compact
clear
update(values)
self
end

# rubocop:enable Naming/MethodParameterName

# Returns a string representation of the sorted array.
Expand Down
41 changes: 41 additions & 0 deletions spec/sorted_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,47 @@
end
end

describe "compact" do
it "should remove nil values from the array" do
# SortedArray can only contain comparable values
# so the only way to have nil values is for all values to be nil
array = SortedContainers::SortedArray.new([nil, nil, nil, nil, nil])
expect(array.compact).to eq(SortedContainers::SortedArray.new)
end

it "should return the array if there are no nil values" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.compact).to eq(array)
end

it "should return the array if the array is empty" do
array = SortedContainers::SortedArray.new
expect(array.compact).to eq(array)
end
end

describe "compact!" do
it "should remove nil values from the array" do
# SortedArray can only contain comparable values
# so the only way to have nil values is for all values to be nil
array = SortedContainers::SortedArray.new([nil, nil, nil, nil, nil])
array.compact!
expect(array).to eq(SortedContainers::SortedArray.new)
end

it "should return the array if there are no nil values" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
array.compact!
expect(array).to eq(SortedContainers::SortedArray.new([1, 2, 3, 4, 5]))
end

it "should return the array if the array is empty" do
array = SortedContainers::SortedArray.new
array.compact!
expect(array).to eq(SortedContainers::SortedArray.new)
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 9efb6e3

Please sign in to comment.