Class: Hone::Patterns::ShuffleFirst
- Defined in:
- lib/hone/patterns/shuffle_first.rb
Overview
Pattern: array.shuffle.first -> array.sample
shuffle.first shuffles the entire array then takes the first element. sample directly selects a random element without creating intermediate array.
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/shuffle_first.rb', line 13 def visit_call_node(node) super # Look for: .first where receiver is .shuffle return unless node.name == :first && node.arguments.nil? receiver = node.receiver return unless receiver.is_a?(Prism::CallNode) && receiver.name == :shuffle add_finding( node, message: "Use `.sample` instead of `.shuffle.first` to avoid shuffling entire array", speedup: "Avoids O(n) shuffle and intermediate array allocation" ) end |