sindresorhus/eslint-plugin-unicorn
`no-array-for-each` bad autofix with `Map`
Closed
#1,452 opened on Jul 27, 2021
bughelp wantedtypes
Repository metrics
- Stars
- (5,022 stars)
- PR merge metrics
- (Avg merge 1d 16h) (399 merged PRs in 30d)
Description
When the no-array-for-each rule is enabled (as recommended) it reports errors when forEach is used with other types that aren’t arrays, like Map or Set. (Or any custom object with a forEach method potentially.)
const map = new Map();
map.forEach((i) => console.log(i));
// ^^^^^^^
// Error: Do not use `Array#forEach(…)`
const set = new Set();
set.forEach((i) => console.log(i));
// ^^^^^^^
// Error: Do not use `Array#forEach(…)`
This is most important for Map, where forEach passes the mapped value as the first argument to its callback, but the current auto-fix (for...of) will pass [key, value]:
const map = new Map([['key', 'value']]);
// Before auto-fix
map.forEach((value) => console.log(value)); // 'value'
// After auto-fix
for (const value of map) {
console.log(value); // ['key', 'value']
}