Class: Hone::Patterns::HashKeysInclude
- Defined in:
- lib/hone/patterns/hash_keys_include.rb
Overview
Pattern: hash.keys.include?(key) -> hash.key?(key)
keys.include? creates an array of all keys then searches it (O(n)). key? does a direct hash lookup (O(1)).
Instance Attribute Summary
Attributes inherited from Base
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 |
# File 'lib/hone/patterns/hash_keys_include.rb', line 13 def visit_call_node(node) super # Look for: .include?(x) where receiver is .keys return unless node.name == :include? && node.arguments&.arguments&.size == 1 receiver = node.receiver return unless receiver.is_a?(Prism::CallNode) && receiver.name == :keys add_finding( node, message: "Use `.key?(k)` instead of `.keys.include?(k)` for O(1) lookup without array allocation", speedup: "O(n) to O(1), avoids allocating array of all keys" ) end |