Class: Hone::Patterns::SortByLast
- Defined in:
- lib/hone/patterns/sort_by_last.rb
Overview
Pattern: array.sort_by { }.last -> array.max_by { }
sort_by { block }.last sorts the entire array then takes the last element. max_by { block } directly finds the maximum 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_last.rb', line 13 def visit_call_node(node) super # Look for: .last where receiver is .sort_by { block } return unless node.name == :last && 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 `.max_by { }` instead of `.sort_by { }.last` to avoid sorting entire array", speedup: "Avoids sorting entire array" ) end |