Skip to content

feat: add no-spread-in-reduce rule - #109

Merged
43081j merged 4 commits into
e18e:mainfrom
webpro:rule-no-spread-in-reduce
May 11, 2026
Merged

43081j merged 4 commits into
e18e:mainfrom
webpro:rule-no-spread-in-reduce

Conversation

@webpro

@webpro webpro commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

New no-spread-in-reduce rule: spreading the accumulator inside .reduce() rebuilds it every step, which is O(N²). The rule flags it and points at the spread; the user mutates (acc.push(x); return acc) or restructures (flatMap, Object.fromEntries) instead.

A real fix this catches (heimdall2 vuln-merging reducer):

// before — O(N²)
list.reduce((acc, cur) => {
  const i = acc.findIndex(v => v.id === cur.id);
  if (i === -1) return [...acc, cur];                  // ← flagged
  acc[i].components.push(...cur.components);
  return acc;
}, []);

// after — O(N)
list.reduce((acc, cur) => {
  const i = acc.findIndex(v => v.id === cur.id);
  if (i === -1) { acc.push(cur); return acc; }
  acc[i].components.push(...cur.components);
  return acc;
}, []);

Commits

This PR is two commits that you can land together or independently:

  1. feat: flag spread of accumulator inside reduce callback — the core rule. Flags the direct shape (acc, x) => [...acc, x] (and object-spread, reduceRight, function-expression callbacks, [x, ...acc] / {k: v, ...acc} — position doesn't change the perf cost).

  2. feat: also flag conditional, destructured, and aliased accumulators — broadens detection to:

    • Conditional returns: if (cond) return [...acc, x]; return acc; walks both arms.
    • Destructured accumulator: ({list}, x) => ({list: [...list, x]}) treats every name bound by the param pattern (with renames) as an accumulator name.
    • Top-level aliases: const a = acc; / const {list} = acc; hoist into the accumulator name set.

    If you'd rather keep the rule small for the first cut, the second commit can be dropped — the first commit lands a useful rule on its own. The second commit catches 2 additional real heimdall2 hits the first commit misses.

Design notes

  • Not in recommended — opt-in only.
  • No autofix in this PR. Considered, but only a narrow subset is mechanically safe (spread-first append-only, with a fresh []/{} initial). Happy to add it as a suggest in a follow-up if you want it.
  • Out of scope: acc.concat(x) and Object.assign({}, acc, x) (same perf, but a different rule's name); [...acc.slice(...), x] (false-positive risk too high without semantic info).

Test plan

  • npm test — 697 tests pass (28 in this rule, including spread position, conditional branches, destructured params, aliased acc, nested-function skip)
  • npm run build
  • npm run lint
  • Ran the rule against knip + 9 cloned consumer codebases. 7 real-world hits across 4 of them (knip 1, rocicorp/mono 3, vona 1, heimdall2 2). All sampled hits are real [...acc, x] / {...acc, k: v} accumulators. No false positives. The 2 heimdall2 hits are unique to the second commit (conditional-branch shapes the first commit doesn't reach).

webpro added 2 commits May 4, 2026 10:01
…allback

`arr.reduce((acc, x) => [...acc, x], [])` rebuilds the accumulator on
every step, copying all N entries each time — O(N²) in total. Same
for `({...acc, [k]: v})`. Mutating (`acc.push(x); return acc`) or
producing the structure once (`Object.fromEntries`, `flatMap`) keeps
it linear.

Flags `reduce` and `reduceRight` callbacks (arrow or function) where
the returned expression is an array or object literal containing a
spread of the accumulator parameter — at any position, not just first
(`[x, ...acc]` and `{k: v, ...acc}` have the same cost). Looks at the
expression body or the last `return` of a block body. Out of scope:
destructured params, aliased accumulators, conditional returns. Not
in `recommended` — opt-in only.
…liased accumulators

The original rule only inspected the last `return` of a callback whose
first param was a plain Identifier. That missed three real shapes of
the same O(N²) bug:

- conditional returns: `if (cond) return [...acc, x]; return acc;`
  examines the `if` branch too.
- destructured accumulator: `({list}, x) => ({list: [...list, x]})`
  treats every name bound by the param pattern (with renames and
  defaults) as an accumulator name.
- aliased accumulator: `{ const a = acc; return [...a, x]; }` and
  `{ const {list} = acc; return [...list, x]; }` hoist names declared
  at the top of the body that resolve to the accumulator.

Walks the whole returned expression for any spread of an accumulator-
bound name (using the parser's visitor keys) so the destructured case
`{list: [...list, x]}` — where the spread sits inside a rebuilt
shape — is caught. Skips nested functions; their returns belong to
themselves.

Surfaces two additional real hits on heimdall2 (a fingerprint reducer
and a vuln-merging reducer), both conditional-branch shapes the prior
implementation missed.
@webpro
webpro force-pushed the rule-no-spread-in-reduce branch from 61cc988 to c416937 Compare May 4, 2026 08:01
43081j
43081j previously approved these changes May 11, 2026
@43081j
43081j merged commit 47974f6 into e18e:main May 11, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants