Class: Hone::Patterns::MapSelectChain

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

Overview

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

Chaining .map and .select creates an intermediate array. Using .filter_map combines both operations in one pass.

From sqids-ruby commit aa4e253

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

def visit_call_node(node)
  super

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

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

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