sindresorhus/eslint-plugin-unicorn

Add auto-fix for `no-array-reduce`

Closed

#1,291 opened on May 18, 2021

 (2 comments) (2 reactions) (0 assignees)JavaScript (468 forks)user submission
enhancementhelp wanted

Repository metrics

Stars
 (5,022 stars)
PR merge metrics
 (Avg merge 1d 16h) (399 merged PRs in 30d)

Description

 const foo = array.reduce(callback, initValue);

->

let foo = initValue;
for (const [index, element] of array.entries()) {
  foo  = callback(foo, element, index, array);

  // Or safer
  // foo  = callback.call(array, foo, element, index, array); 
}

 const foo = array.reduce(callback); // No inital value

->

let foo;
for (const [index, element] of array.entries()) {
  if (index === 0) {
   foo = element;
   continue;
  }
  foo  = callback(foo, element, index, array);
}

 const foo = array.reduce((accumulator, element, index, array) => {
	return doThingsWith(accumulator, element, index, array)
}, initValue);

->

let foo = initValue;
for (const [index, element] of array.entries()) {
  foo  = doThingsWith(foo, element, index, array);
}

Contributor guide