redline
MediumPerformancespread-accumulator

Quadratic reduce

Quadratic reduce. Copies the accumulator on every step of reduce. That's O(n²) for a loop that should be O(n).

This is how the comment reads inline, under the flagged line.

Why it matters

{...acc, [k]: v} inside reduce rebuilds the whole object each iteration. Fine for 10 items, a stall for 10,000.

What to do

Mutate a local accumulator, or use Object.fromEntries / new Map(...).

Examples

Flagged
items.reduce((acc, i) => ({ ...acc, [i.id]: i }), {});
Better
Object.fromEntries(items.map((i) => [i.id, i]));

What it catches

It reads a pattern on each line, aware of strings and comments. Languages: TypeScript and JavaScript. Scope: All files. These cases are the rule's own tests: the first set must be flagged and the second must not.

Flagged

const m = xs.reduce((acc, x) => ({ ...acc, [x.id]: x }), {});

Left alone

const m = Object.fromEntries(xs.map((x) => [x.id, x]));

Research

`{...acc}` or `[...acc]` inside `reduce`. Copying the accumulator on each step makes a linear loop quadratic.

  • no outside source yet

Turn it off or change it

In a config file for the CLI, or in the API's rules field:

{
  "rules": {
    "disable": [
      "spread-accumulator"
    ],
    "severity": {
      "spread-accumulator": "low"
    }
  }
}

Read the source or report a false positive.