sindresorhus/eslint-plugin-unicorn

Rule proposal: `no-complex-iteratee-expression`

Chiusa

#1044 aperta il 20 gen 2021

 (3 commenti) (3 reazioni) (0 assegnatari)JavaScript (468 fork)user submission
help wantednew rule

Metriche repository

Star
 (5022 stelle)
Metriche merge PR
 (Merge medio 1g 16h) (399 PR mergiate in 30 g)

Descrizione

How about forcing the looped expression to be one of:

  • a variable (x)
  • a property access (x.a.b)
  • a single function call with no arguments (x(), x.a.b())
  • one of built-in function calls commonly used for iteration (Object.keys(x)/Object.values(x)/Object.entries(x))

Otherwise force the user to define a variable before the loop (may be possible to auto-fix, the iteratee variable name could be the pluralized name of the element variable).

Originally from https://github.com/sindresorhus/eslint-plugin-unicorn/issues/846#issuecomment-703317406

Fail

for (const x of xs.filter(x => shouldKeep(x))) {
	console.log(x)
}

Pass

const filteredXs = xs.filter(x => shouldKeep(x))

for (const x of filteredXs) {
	console.log(x)
}
for (const x of Object.values(xs)) {
	console.log(x)
}

Guida contributor