Skip to content

Commit

Permalink
Use default map implementation for SortedArray
Browse files Browse the repository at this point in the history
  • Loading branch information
GarrisonJ committed May 16, 2024
1 parent 9acc807 commit 01f18d4
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 33 deletions.
20 changes: 0 additions & 20 deletions lib/sorted_containers/sorted_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -358,26 +358,6 @@ def clear
self
end

# Calls the block, if given, with each element of +self+;
# returns a new +SortedArray+ whose elements are the return values from the block.
#
# If no block is given, returns an Enumerator.
#
# @yield [value] The block to map with.
# @return [SortedArray, Enumerator] The mapped array.
def map
return to_enum(:map) unless block_given?

new_values = []
# rubocop:disable Style/MapIntoArray
each { |value| new_values << yield(value) }
# rubocop:enable Style/MapIntoArray
# Experimitation shows that it's faster to add all values at once
# rather than adding them one by one
self.class.new(new_values, load_factor: @load_factor)
end
alias collect map

# Calls the block, if given, with each element of +self+;
# returns +self+ after the block has been executed.
#
Expand Down
15 changes: 2 additions & 13 deletions spec/sorted_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@
describe "collect" do
it "should return a new array with the results of running the block once for every element" do
array1 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5]).collect { |i| i * 2 }
array2 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5].collect { |i| i * 2 })
array2 = [1, 2, 3, 4, 5].collect { |i| i * 2 }
expect(array1).to eq(array2)
end

Expand All @@ -466,25 +466,14 @@
expect(array.collect).to be_a(Enumerator)
end

it "should return an enumerator if no block is given and the array is empty" do
array = SortedContainers::SortedArray.new
expect(array.collect).to be_a(Enumerator)
end

it "should return an enumerator that loops through the array" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.collect.to_a).to eq([1, 2, 3, 4, 5])
end

it "should keep array sorted after operation" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
array = array.collect { |i| i * -1 }
expect(array.to_a).to eq([-5, -4, -3, -2, -1])
end

it "map is an alias for collect" do
array1 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5]).map { |i| i * 2 }
array2 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5].collect { |i| i * 2 })
array2 = SortedContainers::SortedArray.new([1, 2, 3, 4, 5]).collect { |i| i * 2 }
expect(array1).to eq(array2)
end
end
Expand Down

0 comments on commit 01f18d4

Please sign in to comment.