class RuboCop::Cop::Performance::FlatMap
- 1, 2, 3, 4].collect { |e| [e, e
-
}.flatten
[1, 2, 3, 4].map { |e| [e, e] }.flatten
[1, 2, 3, 4].flat_map { |e| [e, e] }
# good
[1, 2, 3, 4].collect { |e| [e, e] }.flatten(1)
[1, 2, 3, 4].map { |e| [e, e] }.flatten(1)
# bad
@example
change them to use ‘flat_map { … }` instead.
Identifies usages of `map { … }.flatten` and
def autocorrect(corrector, node)
def autocorrect(corrector, node) map_node, _first_method, _flatten, params = flat_map_candidate?(node) flatten_level, = *params.first return unless flatten_level map_send_node = map_node.block_type? ? map_node.send_node : map_node range = range_between(map_node.source_range.end_pos, node.source_range.end_pos) corrector.remove(range) corrector.replace(map_send_node.loc.selector, 'flat_map') end
def offense_for_levels(node, map_node, first_method, flatten)
def offense_for_levels(node, map_node, first_method, flatten) message = MSG + FLATTEN_MULTIPLE_LEVELS register_offense(node, map_node, first_method, flatten, message) end
def offense_for_method(node, map_node, first_method, flatten)
def offense_for_method(node, map_node, first_method, flatten) register_offense(node, map_node, first_method, flatten, MSG) end
def on_send(node)
def on_send(node) flat_map_candidate?(node) do |map_node, first_method, flatten, params| flatten_level, = *params.first if cop_config['EnabledForFlattenWithoutParams'] && !flatten_level offense_for_levels(node, map_node, first_method, flatten) elsif flatten_level == 1 offense_for_method(node, map_node, first_method, flatten) end end end
def register_offense(node, map_node, first_method, flatten, message)
def register_offense(node, map_node, first_method, flatten, message) map_send_node = map_node.block_type? ? map_node.send_node : map_node range = range_between(map_send_node.loc.selector.begin_pos, node.source_range.end_pos) message = format(message, method: first_method, flatten: flatten) add_offense(range, message: message) do |corrector| autocorrect(corrector, node) end end