Sha256: 5567acad22d020dc0d1c3877847bd5674dc21bd8c2d39cf1b51e37204d7936c6

Contents?: true

Size: 1.3 KB

Versions: 12

Compression:

Stored size: 1.3 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 `%<prefer>s` instead.'

        def on_block(node)
          sort_with_block?(node) do |send, var_a, var_b, body|
            replaceable_body?(body, var_b, var_a) do
              register_offense(send, node)
            end
          end
        end

        def on_numblock(node)
          sort_with_numblock?(node) do |send, arg_count, body|
            next unless arg_count == 2

            replaceable_body?(body, :_2, :_1) do
              register_offense(send, node)
            end
          end
        end

        private

        def register_offense(send, node)
          range = sort_range(send, node)
          prefer = "sort#{send.loc.dot.source}reverse"

          message = format(MSG, prefer: prefer)

          add_offense(range, message: message) do |corrector|
            corrector.replace(range, prefer)
          end
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 4 rubygems

Version Path
rubocop-performance-1.23.1 lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.23.0 lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.22.1 lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.22.0 lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.21.1 lib/rubocop/cop/performance/sort_reverse.rb
katalyst-govuk-formbuilder-1.9.2 vendor/bundle/ruby/3.3.0/gems/rubocop-performance-1.21.0/lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.21.0 lib/rubocop/cop/performance/sort_reverse.rb
mlh-rubocop-config-1.0.3 vendor/bundle/ruby/3.2.0/gems/rubocop-performance-1.20.2/lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.20.2 lib/rubocop/cop/performance/sort_reverse.rb
getargv-0.3.3-universal-darwin vendor/bundle/ruby/3.3.0/gems/rubocop-performance-1.20.1/lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.20.1 lib/rubocop/cop/performance/sort_reverse.rb
rubocop-performance-1.20.0 lib/rubocop/cop/performance/sort_reverse.rb