Class: Hone::Patterns::SortByFirst
- Defined in:
- lib/hone/patterns/sort_by_first.rb
Overview
Pattern: array.sort_by { }.first -> array.min_by { }
sort_by { block }.first sorts the entire array then takes the first element. min_by { block } directly finds the minimum 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 28 |
# File 'lib/hone/patterns/sort_by_first.rb', line 13 def visit_call_node(node) super # Look for: .first where receiver is .sort_by { block } return unless node.name == :first && node.arguments.nil? receiver = node.receiver return unless receiver.is_a?(Prism::CallNode) && receiver.name == :sort_by return unless block_attached?(receiver) add_finding( node, message: "Use `.min_by { }` instead of `.sort_by { }.first` to avoid sorting entire array", speedup: "Avoids sorting entire array" ) end |