js-emacs / js2-refactor.el

A JavaScript refactoring library for emacs
GNU General Public License v3.0
374 stars 47 forks source link

extract function with a selected region extracts the whole line #121

Open ArneBab opened 4 years ago

ArneBab commented 4 years ago

When using C-c RET e f on a selected region, rs2-refactor extracts the whole line, but my intention is to refactor only the selected region, for example the condition in an if-statement.

In the following example the selected region is indicated by ^ and $:

if (^foo && (bar === 'bar' || moo)$) {
    return cow;
}

I expected js2r-extract-function to change the code to the following:

if (fooOrBar(foo, bar, moo)) {
    return cow;
}
…
function fooOrBar(foo, bar, moo) {
   return foo && (bar === 'bar' || moo);
}

Instead the refactoring creates the following:

fooOrBar(foo, bar, moo, cow);
…
function fooOrBar(foo, bar, moo, cow) {
  if (foo && (bar === 'bar' || moo)) {
    return cow;
  }
}
ArneBab commented 4 years ago

I see an even stronger version of this: Extracting the region in an if-clause extracts the whole if-block:

Minimal broken example:

function something (foo) {
  let variable = 0;
  if (foo?.length > 0) { // selected region from foo to 0
    variable = foo;
  }
  return variable;
}

Running js2r-extract-function and giving it the new name longFoo yields:

function longFoo(variable, foo) {
  if (foo?.length > 0) {
    variable = foo;
  }
}

function something (foo) {
  let variable = 0;
  longFoo(variable, foo);
  return variable;
}

But it should create:

function longFoo (foo) {
  return foo?.length > 0;
}

function something (foo) {
  let variable = 0;
  if (longFoo(foo)) {
    variable = foo;
  }
  return variable;
}