Class: Hone::Patterns::TimesMap

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

Overview

Pattern: n.times.map { } -> Array.new(n) { }

times.map creates an Enumerator then maps over it. Array.new(n) { } directly creates the array with the block values, avoiding the Enumerator overhead.

Examples:

# Bad: creates Enumerator then maps
5.times.map { |i| i * 2 }
# Good: direct array creation
Array.new(5) { |i| i * 2 }

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



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/hone/patterns/times_map.rb', line 20

def visit_call_node(node)
  super

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

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

  add_finding(
    node,
    message: "Use `Array.new(n) { }` instead of `n.times.map { }` to avoid Enumerator overhead",
    speedup: "Avoids Enumerator overhead"
  )
end