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

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

Open yvele opened this issue 1 year ago • 5 comments

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:

  • https://github.com/sindresorhus/eslint-plugin-unicorn/issues/2045
  • https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1714

yvele avatar May 13 '24 09:05 yvele

Please fill out the title.

sindresorhus avatar May 13 '24 09:05 sindresorhus

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()

fisker avatar May 13 '24 10:05 fisker

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?)

yvele avatar May 13 '24 12:05 yvele

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

silverwind avatar May 13 '24 12:05 silverwind

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? 🤔

yvele avatar May 13 '24 15:05 yvele