Class: Hone::Patterns::SortFirst

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

Overview

Pattern: array.sort.first -> array.min, array.sort.last -> array.max

sort.first/last sorts the entire array O(n log n) then takes one element. min/max finds the element in a single O(n) pass without sorting.

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



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

def visit_call_node(node)
  super

  return unless %i[first last].include?(node.name) && node.arguments.nil?

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

  case [receiver.name, node.name]
  when [:sort, :first]
    add_finding(
      node,
      message: "Use `.min` instead of `.sort.first` to find minimum in O(n) without sorting",
      speedup: "O(n log n) sort to O(n) single pass, no intermediate array"
    )
  when [:sort, :last]
    add_finding(
      node,
      message: "Use `.max` instead of `.sort.last` to find maximum in O(n) without sorting",
      speedup: "O(n log n) sort to O(n) single pass, no intermediate array"
    )
  when [:sort_by, :first]
    return unless block_attached?(receiver)
    add_finding(
      node,
      message: "Use `.min_by { }` instead of `.sort_by { }.first` to find minimum in O(n)",
      speedup: "O(n log n) sort to O(n) single pass, no intermediate array"
    )
  when [:sort_by, :last]
    return unless block_attached?(receiver)
    add_finding(
      node,
      message: "Use `.max_by { }` instead of `.sort_by { }.last` to find maximum in O(n)",
      speedup: "O(n log n) sort to O(n) single pass, no intermediate array"
    )
  end
end