实现说明
逻辑集中在函数 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);