Class: Hone::Patterns::SelectMap

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

Overview

Pattern: array.select { }.map { } -> array.filter_map { }

select.map creates an intermediate array from select, then maps over it. filter_map combines both operations in a single pass, avoiding the 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



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/hone/patterns/select_map.rb', line 14

def visit_call_node(node)
  super

  # Look for: .map { } where receiver is .select { }
  return unless node.name == :map && block_attached?(node)

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

  add_finding(
    node,
    message: "Use `.filter_map { }` instead of `.select { }.map { }` to avoid intermediate array",
    speedup: "Avoids intermediate array"
  )
end