eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: `prefer-array-from`
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))
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
This should handle for await..of
in the future as per https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1712#issuecomment-1028915692
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:
so it doesn't seem to be worth an exception from the rule aboveArray.from(it, a => 2) [...it].map(a => 2)