Class: Hone::Patterns::SortReverse

Inherits:
Base
  • Object
show all
Defined in:
lib/hone/patterns/sort_reverse.rb

Overview

Pattern: array.sort.reverse -> array.sort { |a, b| b <=> a }

Calling .sort.reverse creates an intermediate sorted array, then reverses it. Sorting with a descending comparator avoids the intermediate array allocation.

Example:

# Bad - creates intermediate array
array.sort.reverse

# Good - sorts in descending order directly
array.sort { |a, b| b <=> a }

Note: For sort_by, use: array.sort_by { |x| -x.value } for numeric values

Instance Attribute Summary

Attributes inherited from Base

#findings

Instance Method Summary collapse

Methods inherited from Base

#add_finding, inherited, #initialize, scan_file

Constructor Details

This class inherits a constructor from Hone::Patterns::Base

Instance Method Details

#visit_call_node(node) ⇒ Object



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
# File 'lib/hone/patterns/sort_reverse.rb', line 23

def visit_call_node(node)
  super

  # Look for: .reverse where receiver is .sort or .sort_by
  return unless node.name == :reverse

  receiver = node.receiver
  return unless receiver.is_a?(Prism::CallNode)

  case receiver.name
  when :sort
    # .sort.reverse -> .sort { |a, b| b <=> a }
    add_finding(
      node,
      message: "Use `.sort { |a, b| b <=> a }` instead of `.sort.reverse` to avoid intermediate array",
      speedup: "Avoids creating intermediate sorted array"
    )
  when :sort_by
    # .sort_by { }.reverse -> consider negating the sort key
    return unless block_attached?(receiver)

    add_finding(
      node,
      message: "Consider negating the sort key in `.sort_by` instead of calling `.reverse`",
      speedup: "Avoids creating intermediate sorted array"
    )
  end
end