Class: Hone::Patterns::ArrayCompact

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

Overview

Pattern: array.reject { |x| x.nil? } -> array.compact array.select { |x| !x.nil? } -> array.compact

compact is implemented in C and optimized for removing nil values. Using reject/select with a block for nil checking is slower and less clear.

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
30
31
32
33
34
35
36
# File 'lib/hone/patterns/array_compact.rb', line 14

def visit_call_node(node)
  super

  return unless %i[reject select].include?(node.name)
  return unless block_attached?(node)

  block = node.block
  return unless block.is_a?(Prism::BlockNode)

  if node.name == :reject && reject_nil_pattern?(block)
    add_finding(
      node,
      message: "Use `.compact` instead of `.reject { |x| x.nil? }` for optimized nil removal",
      speedup: "Uses optimized C implementation"
    )
  elsif node.name == :select && select_not_nil_pattern?(block)
    add_finding(
      node,
      message: "Use `.compact` instead of `.select { |x| !x.nil? }` for optimized nil removal",
      speedup: "Uses optimized C implementation"
    )
  end
end