Class: Hone::Patterns::ReverseFirst

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

Overview

Pattern: array.reverse.first -> array.last array.reverse.first(n) -> array.last(n).reverse

reverse.first reverses the entire array then takes the first element(s). Using last directly accesses the end of the array without creating an intermediate reversed array.

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



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/hone/patterns/reverse_first.rb', line 15

def visit_call_node(node)
  super

  # Look for: .first or .first(n) where receiver is .reverse
  return unless node.name == :first

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

  if node.arguments.nil?
    add_finding(
      node,
      message: "Use `.last` instead of `.reverse.first` to avoid reversing entire array",
      speedup: "Avoids reversing entire array"
    )
  else
    add_finding(
      node,
      message: "Use `.last(n).reverse` instead of `.reverse.first(n)` to avoid reversing entire array",
      speedup: "Avoids reversing entire array"
    )
  end
end