← 中文资源

简体中文版本

数组对比找出新增与移除项

把前后两个快照各建成 Set 后双向过滤,得到 added 与 removed 两个方向的变化;同时存在的条目两边都不出现,快照内部的重复项也不会产生重复差分。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

added:   [ 'billing.js', 'tests.js' ]
removed: [ 'legacy.js' ]
overlap -> added: [] | removed: [ 'a' ]
dupes   -> added: [] | removed: [ 'y' ]

实现说明

逻辑集中在函数 diff里。 结果是全新构造,调用方可以放心保留自己的原件。

使用要点

  • 跑完文件,输出里会留下标记——added:、removed:、overlap -> added:。

常见问题

diff 会修改传入的参数吗?

没有原地修改——函数读取输入并返回新值。

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 diff。

入口签名:function diff(previous, current)

核心语句

const before = new Set(previous);
const after = new Set(current);

代码示例

// Compare two snapshots of a list: which items arrived, which left.
function diff(previous, current) {
  const before = new Set(previous);
  const after = new Set(current);
  return {
    added: current.filter((item) => !before.has(item)),
    removed: previous.filter((item) => !after.has(item)),
  };
}

const yesterday = ['orders.js', 'auth.js', 'utils.js', 'legacy.js'];
const today = ['orders.js', 'auth.js', 'billing.js', 'utils.js', 'tests.js'];

const { added, removed } = diff(yesterday, today);
console.log('added:  ', added);
console.log('removed:', removed);

// Items present in both snapshots stay out of both results.
const overlap = diff(['a', 'b', 'c'], ['b', 'c']);
console.log('overlap -> added:', overlap.added, '| removed:', overlap.removed);

// Duplicate entries inside one snapshot do not leak into the diff,
// because each side filters against the other snapshot's Set.
const duplicated = diff(['x', 'x', 'y'], ['x']);
console.log('dupes   -> added:', duplicated.added, '| removed:', duplicated.removed);