Skip to content
Sarj Code Standards

no-reduce-accumulator-copy

Review copies of the accumulated collection inside a built-in reduce callback.

Why

Copying a growing accumulator at every step can make collection quadratic instead of linear in its output size.

Fix

Use map or flatMap where their semantics match, or append into a fresh locally owned accumulator. Preserve retained snapshots and shared state.

Examples

Before — flagged Repeated concatenation copies prior report rows
src/reports.ts
declare const pages: string[][];
const rows = pages.reduce<string[]>((acc, page) => acc.concat(page), []);
After — preferred Flatten report rows without copying the accumulated prefix
src/reports.ts
declare const pages: string[][];
const rows = pages.flatMap((page) => page);
Before — flagged Retain fresh seed and accumulator identities — before
src/example.ts
declare const pages: string[][];
const seed: string[] = [];
pages.reduce((acc, page) => {
const previous = acc;
return [...previous, ...page];
}, seed);
After — preferred Retain fresh seed and accumulator identities — after
src/example.ts
declare const pages: string[][];
pages.flatMap((page) => page);

References