Skip to content

Commit

Permalink
Merge pull request #391 from fatkodima/improve-map_compact-for-safe-h…
Browse files Browse the repository at this point in the history
…andling

Improve `Performance/MapCompact` to handle more safe navigation calls
  • Loading branch information
koic authored Nov 26, 2023
2 parents 6ba69de + 6dbda67 commit eb714d9
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog/change_improve_performance_map_compact_to.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#389](https://github.com/rubocop/rubocop-performance/issues/389): Improve `Performance/MapCompact` to handle more safe navigation calls. ([@fatkodima][])
4 changes: 2 additions & 2 deletions lib/rubocop/cop/performance/map_compact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ class MapCompact < Base

def_node_matcher :map_compact, <<~PATTERN
{
(send
(call
$(call _ {:map :collect}
(block_pass
(sym _))) _)
(send
(call
(block
$(call _ {:map :collect})
(args ...) _) _)
Expand Down
24 changes: 23 additions & 1 deletion spec/rubocop/cop/performance/map_compact_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
RUBY
end

it 'registers an offense when using `collection.map(&:do_something)&.compact`' do
it 'registers an offense when using `collection&.map(&:do_something).compact`' do
expect_offense(<<~RUBY)
collection&.map(&:do_something).compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
Expand All @@ -24,6 +24,17 @@
RUBY
end

it 'registers an offense when using `collection&.map(&:do_something)&.compact`' do
expect_offense(<<~RUBY)
collection&.map(&:do_something)&.compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
RUBY

expect_correction(<<~RUBY)
collection&.filter_map(&:do_something)
RUBY
end

it 'registers an offense when using `collection.map { |item| item.do_something }.compact`' do
expect_offense(<<~RUBY)
collection.map { |item| item.do_something }.compact
Expand All @@ -46,6 +57,17 @@
RUBY
end

it 'registers an offense when using `collection&.map { |item| item.do_something }&.compact`' do
expect_offense(<<~RUBY)
collection&.map { |item| item.do_something }&.compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
RUBY

expect_correction(<<~RUBY)
collection&.filter_map { |item| item.do_something }
RUBY
end

it 'registers an offense when using `collection.collect(&:do_something).compact`' do
expect_offense(<<~RUBY)
collection.collect(&:do_something).compact
Expand Down

0 comments on commit eb714d9

Please sign in to comment.