jfmengels/eslint-plugin-fp

Rule proposal: return-in-conditionals

jfmengels opened this issue · 2 comments

Conditionals (in functions) that don't return a value or end the function are most likely causing a side-effect.
In the case when it is used to assign a value to a variable, in order to not have a complex ternary expression, should probably be moved to a separate function.

Switch cases should also return statement and should therefore not use break.

Top-level conditionals should be exempted from this rule, as they can't return values. (bikeshedding here?)

Invalid

function bar(a) {
  let res;
  if (expression) {
    res = 2;
  } else {
    res = 3;
  }
  return foo(res);
}

function switchFn(b) {
  switch(a) {
    case 1:
       doSomething();
       break;
    default:
       doSomethingElse();
       break;
  }
}

Valid

function bar(a) {
  return foo(value(a));
}

function value(a) {
  if (expression) {
    return 2;
  } else {
    return 3;
  }
}

function switchFn(b) {
  switch(a) {
    case 1:
       return doSomething();
    default:
       return doSomethingElse();
  }
}

// Top-level conditionals are okay
if (FOO) {
  foo();
} else {
  bar();
}

Maybe worth splitting the rule into two. One for if and one for switch case

+1