eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule change proposal regarding `prefer-ternary`:
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;
Would it be possible to also detect the following example?
Yes.
Note that they are not really the same, we need check that initial assigned value don't have sideeffect.
This is accepted.
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;
}