sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
3.98k stars 361 forks source link

Rule proposal: Prefer `Array.from(arr, mapFn)` over `Array.from(arr).map(mapFn)` #2357

Open yvele opened 1 month ago

yvele commented 1 month ago

Description

Prefer Array.from(arrayLike, mapFn) over Array.from(arrayLike).map(...)

Prefer directly using Array.from mapFn argument instead of an extra map.

This is supposed to improve performances.

Fail

const foo = Array.from(bar).map(baz);
const foo = Array.from(bar).map((element, i) => baz(element, i));

Pass

const foo = Array.from(bar, baz);
const foo = Array.from(bar, (element, i) => baz(element, i));

Proposed rule name

prefer-array-from-map-fn

Additional Info

This should be automatically fixable by the --fix CLI option.

This looks 🤔 a bit related to:

sindresorhus commented 1 month ago

Please fill out the title.

fisker commented 1 month ago

This rule may conflict with prefer-array-flat-map, I'm not how will ESLint work if we enable both for following code

Array.from(foo).map(bar).flat()
yvele commented 1 month ago

Please fill out the title.

Done

This rule may conflict with prefer-array-flat-map, I'm not how will ESLint work if we enable both for following code

Array.from(foo).map(bar).flat()

We first need to figure out what we want to have

Array.from(foo, bar).flat()

vs

Array.from(foo).flatMap(bar)

In my opinion the flatMap(bar) looks more expressive, because bar is more about flatting than about mapping, does that make sense? From performance perspective they looks the same (do they?)

silverwind commented 1 month ago

Already exists in another plugin: https://github.com/freaktechnik/eslint-plugin-array-func#from-map

yvele commented 1 month ago

Already exists in another plugin: https://github.com/freaktechnik/eslint-plugin-array-func#from-map

Okay cool, thanks 👍

https://www.npmjs.com/package/eslint-plugin-array-func

image

So.. what now? @fisker @sindresorhus I would prefer to stick with eslint-plugin-unicorn only that is well managed and that I trust. Will this feature be added to eslint-plugin-unicorn or should I add an extra eslint-plugin-array-func to my ESLint config? 🤔