@putout/plugin-convert-reduce-to-for-of
v1.4.1
Published
🐊Putout plugin adds ability to convert '.reduce()' to 'for...of'
Downloads
3,331
Maintainers
Readme
@putout/plugin-convert-reduce-to-for-of
The
reduce()
method executes a user-supplied reducer callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.The
for...of
statement creates a loop which invokes a custom iteration hook with statements to be executed for the value of each element of an array.(c) MDN
🐊Putout plugin adds ability to convert .reduce()
to for...of
loop. Merged to @putout/plugin-for-of
.
You should always look at second argument of a reducer since it changes logic drastically and should read back and forth a couple times to understand what is going on.
Recursive functions like
.reduce()
can be powerful but sometimes difficult to understand, especially for less experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using.reduce()
. In cases where.reduce()
is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks.(c) MDN
Check it out in 🐊Putout Editor.
Install
npm i @putout/plugin-convert-reduce-to-for-of -D
Rule
{
"rules": {
"convert-reduce-to-for-of": "on"
}
}
❌ Example of incorrect code
const result = list.reduce((a, b) => a + b, 1);
✅ Example of correct code
let sum = 1;
for (const a of list) {
sum += a;
}
License
MIT