File: sort_reverse.rb

package info (click to toggle)
ruby-rubocop-performance 1.7.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 792 kB
  • sloc: ruby: 6,722; makefile: 8
file content (54 lines) | stat: -rw-r--r-- 1,370 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # This cop 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 < Cop
        include SortBlock

        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(
                node,
                location: range,
                message: message(var_a, var_b)
              )
            end
          end
        end

        def autocorrect(node)
          sort_with_block?(node) do |send, _var_a, _var_b, _body|
            lambda do |corrector|
              range = sort_range(send, node)
              replacement = 'sort.reverse'
              corrector.replace(range, replacement)
            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