Description
When creating an array of a predetermined length (e.g. with Array.from({ length: 5 })), it is common to insert items at each index and/or fill it with items.
I'd like to propose using the built-in mapfn argument for Array.from(iterable, mapfn) in lieu of Array#map() or Array#flatMap() on a newly-created arrays,.
These are the scenarios I think this rule should take into account:
- When creating an array with
Array.from()
- If
.fill().map() is chained to it, suggest moving the map callback into the mapfn argument
- If
.fill().flatMap() is chained to it, suggest moving the flat map callback into the mapfn argument and appending .flat()
If desired, the flatMap portion of the rule could be a configurable option (e.g. allowFlatMap).
Examples
// ❌
Array.from({ length: 5 })
.fill(null)
.map((_, index) => `Item number: ${index}`);
// ✅
Array.from(
{ length: 5 },
(_, index) => `Item number: ${index}`
);
// ❌
Array.from({ length: 5 })
.fill(null)
.flatMap((_, index) => [["something", index]]);
// ✅
Array.from(
{ length: 5 },
(_, index) => [["something", index]]
).flat();
// ❌
Array.from({ length: 5 })
.fill({ something: "special" });
// type: Array<unknown>
// ✅
Array.from(
{ length: 5 },
() => ({ something: "special })
);
// type: Array<{ something: string }>
// ✅
Array.from<{ something: string }>({ length: 5 })
.fill({ something: 'special' });
// type: Array<{ something: string }>
Proposed rule name
One of:
- no-array-from-fill-map
- prefer-array-from-map-fn
- prefer-array-from-init-fn
Additional Info
No response
Description
When creating an array of a predetermined length (e.g. with
Array.from({ length: 5 })), it is common to insert items at each index and/or fill it with items.I'd like to propose using the built-in
mapfnargument forArray.from(iterable, mapfn)in lieu ofArray#map()orArray#flatMap()on a newly-created arrays,.These are the scenarios I think this rule should take into account:
Array.from().fill().map()is chained to it, suggest moving the map callback into themapfnargument.fill().flatMap()is chained to it, suggest moving the flat map callback into themapfnargument and appending.flat()If desired, the flatMap portion of the rule could be a configurable option (e.g.
allowFlatMap).Examples
Proposed rule name
One of:
Additional Info
No response