next-ls icon indicating copy to clipboard operation
next-ls copied to clipboard

workspace command: extract an anonymous function to a private one

Open NJichev opened this issue 1 year ago • 1 comments

A workspace command that extracts an anonymous function to a private one.

Example:

defmodule Example do
  def run(list) do
    square = fn x -> x * x end
    Enum.map(list, square)
  end
end

Hovering the variable of the anonymous function or the anonymous function definition and using the workspace command should result in:

defmodule Example do
  def run(list) do
    Enum.map(list, &square/1)
  end

  defp square(x) do
    x * x
  end
end

Consider the following scenarios:

  • The anonymous function binds variables from out of their scope
square_sum = fn x -> x * x + constant end
# should result in:
defp square_sum(x, constant), do: ...
  • Any function calls should be converted as well: square.(3) -> square(3)
  • An inlined anonymous function that is not bound to a variable, will need a default name to use

NJichev avatar Apr 24 '24 16:04 NJichev

similar to #437 , i think i would expect this work work as follows

defmodule Example do
  def run(list) do
    square = fn x -> x * x end
    Enum.map(list, square)
  end
end

refactors to

defmodule Example do
  def run(list) do
    square = &square/1
    Enum.map(list, square)
  end

  defp square(x) do
    x * x
  end
end

this reduces complexity, and fits with the more intuitive (IMO) behavior if you were to transform an inline anonymous function, like this

defmodule Example do
  def run(list) do
    Enum.map(list, fn x -> x * x end)
  end
end

refactors to

defmodule Example do
  def run(list) do
    Enum.map(list, &square/1)
  end

  defp square(x) do
    x * x
  end
end

mhanberg avatar Apr 24 '24 18:04 mhanberg