Class: RuboCop::Cop::Performance::UnneededSort

Inherits:
Cop
  • Object
show all
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/performance/unneeded_sort.rb

Overview

This cop is used to identify instances of sorting and then taking only the first or last element. The same behavior can be accomplished without a relatively expensive sort by using ‘Enumerable#min` instead of sorting and taking the first element and `Enumerable#max` instead of sorting and taking the last element. Similarly, `Enumerable#min_by` and `Enumerable#max_by` can replace `Enumerable#sort_by` calls after which only the first or last element is used.

Examples:

# bad
[2, 1, 3].sort.first
[2, 1, 3].sort[0]
[2, 1, 3].sort.at(0)
[2, 1, 3].sort.slice(0)

# good
[2, 1, 3].min

# bad
[2, 1, 3].sort.last
[2, 1, 3].sort[-1]
[2, 1, 3].sort.at(-1)
[2, 1, 3].sort.slice(-1)

# good
[2, 1, 3].max

# bad
arr.sort_by(&:foo).first
arr.sort_by(&:foo)[0]
arr.sort_by(&:foo).at(0)
arr.sort_by(&:foo).slice(0)

# good
arr.min_by(&:foo)

# bad
arr.sort_by(&:foo).last
arr.sort_by(&:foo)[-1]
arr.sort_by(&:foo).at(-1)
arr.sort_by(&:foo).slice(-1)

# good
arr.max_by(&:foo)

Constant Summary collapse

MSG =
'Use `%<suggestion>s` instead of '\
'`%<sorter>s...%<accessor_source>s`.'.freeze

Constants included from Util

Util::ASGN_NODES, Util::CONDITIONAL_NODES, Util::EQUALS_ASGN_NODES, Util::LITERAL_REGEX, Util::LOGICAL_OPERATOR_NODES, Util::MODIFIER_NODES, Util::OPERATOR_METHODS, Util::SHORTHAND_ASGN_NODES

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offenses, #processed_source

Instance Method Summary collapse

Methods inherited from Cop

#add_offense, all, autocorrect_incompatible_with, badge, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, #cop_name, cop_name, #correct, department, #duplicate_location?, #excluded_file?, #find_location, #highlights, inherited, #initialize, #join_force?, lint?, match?, #messages, non_rails, #parse, qualified_cop_name, #relevant_file?, #target_rails_version, #target_ruby_version

Methods included from AST::Sexp

#s

Methods included from NodePattern::Macros

#def_node_matcher, #def_node_search, #node_search, #node_search_all, #node_search_body, #node_search_first

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #support_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

begins_its_line?, comment_line?, double_quotes_required?, escape_string, first_part_of_call_chain, interpret_string_escapes, line_range, needs_escaping?, on_node, operator?, parentheses?, same_line?, to_string_literal, to_supported_styles, tokens

Methods included from PathUtil

absolute?, match_path?, pwd, relative_path, reset_pwd, smart_path

Constructor Details

This class inherits a constructor from RuboCop::Cop::Cop

Instance Method Details

#autocorrect(node) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/rubocop/cop/performance/unneeded_sort.rb', line 89

def autocorrect(node)
  sort_node, sorter, accessor = unneeded_sort?(node)

  lambda do |corrector|
    # Remove accessor, e.g. `first` or `[-1]`.
    corrector.remove(
      range_between(
        accessor_start(node),
        node.loc.expression.end_pos
      )
    )

    # Replace "sort" or "sort_by" with the appropriate min/max method.
    corrector.replace(
      sort_node.loc.selector,
      suggestion(sorter, accessor, arg_value(node))
    )
  end
end

#on_send(node) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/rubocop/cop/performance/unneeded_sort.rb', line 74

def on_send(node)
  unneeded_sort?(node) do |sort_node, sorter, accessor|
    range = range_between(
      sort_node.loc.selector.begin_pos,
      node.loc.expression.end_pos
    )

    add_offense(node,
                location: range,
                message: message(node,
                                 sorter,
                                 accessor))
  end
end