Class: Hone::Patterns::ArrayIncludeSet

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

Overview

Pattern: array.include?(x) -> consider Set for repeated lookups

Array#include? is O(n) for each lookup. If performing repeated lookups, converting to Set gives O(1) lookups.

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

def visit_call_node(node)
  super

  # Look for: .include?(x) with one argument
  return unless node.name == :include?
  return unless node.arguments&.arguments&.size == 1

  # Skip if receiver is a known hash method chain (handled by hash_keys_include)
  receiver = node.receiver
  if receiver.is_a?(Prism::CallNode)
    return if receiver.name == :keys || receiver.name == :values
  end

  add_finding(
    node,
    message: "Consider using Set instead of Array#include? for repeated lookups",
    speedup: "O(1) vs O(n) for repeated lookups"
  )
end