Reduce Folds Records Into A Map

Fold an array into a Map of per-key aggregates in one pass: the Map keeps first-seen order, and the object-spread version exposes a per-iteration copy trap.

JavascriptData Integrity

Code

javascriptsnippet
32 lines
const commits = [
  { author: 'ada', files: 3, added: 120 },
  { author: 'lee', files: 1, added: 12 },
  { author: 'ada', files: 2, added: 45 },
  { author: 'lee', files: 4, added: 210 },
];

// reduce 一次遍历同时做分组与多字段聚合:Map 保住键的首次出现序
const stats = commits.reduce((acc, c) => {
  const s = acc.get(c.author) ?? { commits: 0, files: 0, added: 0 };
  s.commits += 1;
  s.files += c.files;
  s.added += c.added;
  acc.set(c.author, s);
  return acc;
}, new Map());

for (const [author, s] of stats) {
  console.log(author, JSON.stringify(s));
}

// 反面教材:箭头函数体里写 (acc, c) => ({ ...acc, ... }) 每轮新建对象,
// 大数组上是 O(n²) 复制 —— 返回同一引用再改字段才是单趟
const totals = commits.reduce(
  (sum, c) => {
    sum.files += c.files;
    sum.added += c.added;
    return sum;
  },
  { files: 0, added: 0 },
);
console.log('totals:', totals);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ada {"commits":2,"files":5,"added":165}
lee {"commits":2,"files":5,"added":222}
totals: { files: 10, added: 387 }

How the snippet works

Repetition is confined to for (const [author, s] of stats) — the rest of the file is straight-line.

Everything operates on top-level bindings: commits, stats, totals.

Applying it

The demo output is labeled (totals:), so every printed line maps back to its originating operation.

Statements that matter

const stats = commits.reduce((acc, c) => {
  const s = acc.get(c.author) ?? { commits: 0, files: 0, added: 0 };
  s.commits += 1;
  s.files += c.files;
  s.added += c.added;
  acc.set(c.author, s);
  return acc;
}, new Map());
sum.files += c.files;
sum.added += c.added;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `commits`, `stats`, `totals`.