Sha256: 55cf484c75de7563dcc4ea590e34b1bd5ac519fd5db83d728c29e795e6357ee9

Contents?: true

Size: 1.1 KB

Versions: 9

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # Identifies places where `sort { |a, b| b <=> a }`
      # can be replaced by a faster `sort.reverse`.
      #
      # @example
      #   # bad
      #   array.sort { |a, b| b <=> a }
      #
      #   # good
      #   array.sort.reverse
      #
      class SortReverse < Base
        include SortBlock
        extend AutoCorrector

        MSG = 'Use `sort.reverse` instead of `%<bad_method>s`.'

        def on_block(node)
          sort_with_block?(node) do |send, var_a, var_b, body|
            replaceable_body?(body, var_b, var_a) do
              range = sort_range(send, node)

              add_offense(range, message: message(var_a, var_b)) do |corrector|
                replacement = 'sort.reverse'

                corrector.replace(range, replacement)
              end
            end
          end
        end

        private

        def message(var_a, var_b)
          bad_method = "sort { |#{var_a}, #{var_b}| #{var_b} <=> #{var_a} }"
          format(MSG, bad_method: bad_method)
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 3 rubygems

Version Path
cm-admin-1.5.22 vendor/bundle/ruby/3.3.0/gems/rubocop-performance-1.14.3/lib/rubocop/cop/performance/sort_reverse.rb
cm-admin-1.5.21 vendor/bundle/ruby/3.3.0/gems/rubocop-performance-1.14.3/lib/rubocop/cop/performance/sort_reverse.rb
cm-admin-1.5.20 vendor/bundle/ruby/3.3.0/gems/rubocop-performance-1.14.3/lib/rubocop/cop/performance/sort_reverse.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-performance-1.14.3/lib/rubocop/cop/performance/sort_reverse.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-performance-1.14.3/lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.14.3 lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.14.2 lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.14.1 lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.14.0 lib/rubocop/cop/performance/sort_reverse.rb