Class: Hone::Patterns::SelectCount

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

Overview

Pattern: array.select { }.count -> array.count { }

select { }.count creates a temporary array of matches then counts it. count { } counts matches directly without intermediate allocation.

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

def visit_call_node(node)
  super

  # Look for: .count/.size/.length (no args) where receiver is .select with block
  return unless %i[count size length].include?(node.name)
  return unless node.arguments.nil?

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

  add_finding(
    node,
    message: "Use `.count { }` instead of `.select { }.#{node.name}` to avoid intermediate array",
    speedup: "Counts directly without allocating intermediate array"
  )
end