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

Rule proposal: `prefer-array-from`

Open Pyrolistical opened this issue 2 years ago • 3 comments

Description

Often no-for-loop results in something that be simplified down to Array.from

Note for even simpler cases are handled by https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1713

This is an alternative to https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1712 and only one of these rules should be implemented. This can been seen as superior to https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1712 as it works for both arrays and iterators.

Original idea: https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1712#issuecomment-1029310144

Fail

const result = []
for (const element of array) {
  result.push(transform(element))
}
const result = []
for (const [index, element] of array.entries()) {
  result[index] = transform(element)
}
const result = []
for (const [index, element] of array.entries()) {
  result.push(anotherArray[index](element))
}

Pass

const result = Array.from(array, (element) => transform(element))
const result = Array.from(array, (element, index) => anotherArray[index](element))

Pyrolistical avatar Feb 03 '22 19:02 Pyrolistical

Another idea would be to roll this into prefer-spread in the form of

const result = [...array].map((element) => transform(element))

Note the reason why spread is needed is lack of .map on iterators, which would be filled by https://github.com/tc39/proposal-iterator-helpers

Pyrolistical avatar Feb 03 '22 19:02 Pyrolistical

This should handle for await..of in the future as per https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1712#issuecomment-1028915692

Pyrolistical avatar Feb 03 '22 19:02 Pyrolistical

This is basically a "prefer array map" that also works for iterators. If the input is an actual array like in your example it's best to just just .map()

Also generally I'm not sure this is worth it for two reasons:

  • there's already a rule the prefers [...it] over Array.from(it)
  • there's not much difference between:
    Array.from(it, a => 2)
    [...it].map(a => 2)
    
    so it doesn't seem to be worth an exception from the rule above

fregante avatar Mar 05 '22 03:03 fregante