eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule change proposal regarding `prefer-ternary`:

Open jroru opened this issue 2 years ago • 4 comments

Description

prefer-ternary currently only supports

'simple' if-else statements, where 'simple' means the consequent and alternate are each one line and have the same basic type and form.

Would it be possible to also detect the following example?:

Fail

const data = getData();
const defaultData = getDefaultData();

let items = defaultData;

if (data.length) {
    items = data;
}

Pass

const data = getData();
const defaultData = getDefaultData();

const items = data.length ? data : defaultData;

jroru avatar Nov 24 '21 20:11 jroru

Would it be possible to also detect the following example?

Yes.

fisker avatar Nov 25 '21 00:11 fisker

Note that they are not really the same, we need check that initial assigned value don't have sideeffect.

fisker avatar Nov 25 '21 01:11 fisker

This is accepted.

sindresorhus avatar Nov 30 '21 12:11 sindresorhus

I started looking at this. A couple of questions:

we need check that initial assigned value don't have sideeffect.

In other words - whether the initially assigned value is not a function call? FAIL

let items = defaultData;

if (data.length) {
    items = data;
}

PASS

let items = getDefaultData();

if (data.length) {
    items = data;
}

How far do we want to go with this enhancement? For instance, what about those cases:

  • multiple statements in if block
let items = defaultData;
let nopers = {};

if (data.length) {
    items = data;
    nopers = 'hey';
    foo();
}
  • Reassignments after the declaration
let items = defaultData;

items = fallbackData;

if (data.length) {
    items = data;
}
  • Side effects between the assignment and if block
let items = defaultData;

sideEffect()

if (data.length) {
    items = data;
}

zaicevas avatar Mar 19 '22 19:03 zaicevas