class RuboCop::Cop::Performance::MapCompact


ary.compact.map(&:foo)
ary.map(&:foo).compact!
ary.filter_map(&:foo)
# good
ary.collect(&:foo).compact
ary.map(&:foo).compact
# bad
@example
—-
[true, false, nil].filter_map(&:itself) #=> [true]
[true, false, nil].compact #=> [true, false]
—-
[source,ruby]

also filters out falsy values, while ‘compact` only gets rid of `nil`.
different results than `filter_map`. As illustrated in the example, `filter_map`
This cop’s autocorrection is unsafe because ‘map { … }.compact` might yield
@safety
This cop identifies places where `map { … }.compact` can be replaced by `filter_map`.
In Ruby 2.7, `Enumerable#filter_map` has been added.

def compact_method_with_final_newline_range(compact_method_range)

def compact_method_with_final_newline_range(compact_method_range)
  range_by_whole_lines(compact_method_range, include_final_newline: true)
end

def invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)

def invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
  compact_node.loc.selector.line == chained_method.loc.last_line
end

def map_method_and_compact_method_on_same_line?(map_node, compact_node)

def map_method_and_compact_method_on_same_line?(map_node, compact_node)
  compact_node.loc.selector.line == map_node.loc.selector.line
end

def on_send(node)

def on_send(node)
  return unless (map_node = map_compact(node))
  compact_loc = node.loc
  range = range_between(map_node.loc.selector.begin_pos, compact_loc.selector.end_pos)
  add_offense(range) do |corrector|
    corrector.replace(map_node.loc.selector, 'filter_map')
    remove_compact_method(corrector, map_node, node, node.parent)
  end
end

def remove_compact_method(corrector, map_node, compact_node, chained_method)

def remove_compact_method(corrector, map_node, compact_node, chained_method)
  compact_method_range = compact_node.loc.selector
  if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) && use_dot?(chained_method) &&
     !map_method_and_compact_method_on_same_line?(map_node, compact_node) &&
     !invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
    compact_method_range = compact_method_with_final_newline_range(compact_method_range)
  else
    corrector.remove(compact_node.loc.dot)
  end
  corrector.remove(compact_method_range)
end

def use_dot?(node)

def use_dot?(node)
  node.respond_to?(:dot?) && node.dot?
end