Skip to content

[HOLD for payment 2024-06-13] [LOW] [Performance] Add no-spread-in-reduce to avoid recreating array in reduce method #42414

@mountiny

Description

@mountiny

Problem

When you use the spread operator in an array reduce, it often leads to a partial object being copied over and over again in a loop.

// BAD
const reducedObject = myArray.reduce(
    (acc, key) => ({
        ...acc,
        [key]: someOtherObject[key],
    }),
    {},
);

Especially with large objects, this is very inefficient because ...acc will unnecessarily copy the full object on each iteration, rather than just adding the single key we want to add.

Solution

Prohibit this pattern with a new ESLint rule - no-spread-in-reduce. The above example would result in a lint error, and you might fix it with something more simple and efficient, like this:

GOOD
const reducedObject = myArray.reduce(
    (acc, key) => {
        acc[key] = someOtherObject[key];
        return acc;
    },
    {},
)

@kacper-mikolajczak

Upwork Automation - Do Not Edit
  • Upwork Job URL: https://www.upwork.com/jobs/~011102640f041d624c
  • Upwork Job ID: 1792878366584131584
  • Last Price Increase: 2024-05-21
  • Automatic offers:
    • DylanDylann | Reviewer | 0
Issue OwnerCurrent Issue Owner: @garrettmknight

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionDailyKSv2ExternalAdded to denote the issue can be worked on by a contributorNewFeatureSomething to build that is a new item.

Type

No type
No fields configured for issues without a type.

Projects

Status
Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions