New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rule proposal: prefer-array-find
#730
Comments
Failconst item = array.filter(x => x === '馃').shift(); |
Accepted. PR welcome. |
sindresorhus Asked about this in #735 (comment) const result = array.filter(x => x === '馃');
const item = result[0]; To support this, we need check
const result = array.find(x => x === '馃');
const item = result; The name may confuse people
const item = array.find(x => x === '馃'); problem is the
const result = array.filter(x => x === '馃');
const item = result.shift(); const result = array.filter(x => x === '馃');
const [item] = result; too? @oscarmarcelo What do you think? |
Honestly, I don't understand the implications of the first two points, but I totally agree with the third one! |
I have one concern about side effects of const arrayTypeObjects = foo.filter(object => {
const isArray = Array.isArray(object.data);
object.isArray = isArray; // <-- also add a mark to every object
return isArray;
});
const firstArray = arrayTypeObjects[0];
doSomething(firstArray);
for (const object of foo) {
if (object.isArray) { // <-- rely on the mark set above
doSomething(object.data)
} else {
doSomethingDifferent(object.data)
}
} If we fix For this reason, I suggest auto-fix under an option like this {
'unicorn/prefer-array-find': [
'error',
{
ignoreSideEffect: true,
operatorForDefaultValueOfDestructuring: '??'
}
]
}
|
Nice find! I didn't think about this to this level of detail! 馃槂 |
I thought this rule is easy too, actually it only took about 30 mins to finish the first implementation, then I dig more and more deeper... |
Prefer
.find()
over.filter()[0]
, sincefind
breaks the loop as soon as it finds a match.Fail
Pass
The text was updated successfully, but these errors were encountered: