← 中文资源

简体中文版本

Set 的差集与对称差集

用 difference 求单向删除、镜像调用求新增、symmetricDifference 一次拿到两侧变更,并用「并集减交集」交叉验证部署 diff 的正确性。

阅读英文原文

运行结果

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

removed: [ 'auth', 'admin' ]
added: [ 'reports' ]
changed: [ 'auth', 'admin', 'reports' ]
agrees: true

实现说明

各个操作都建立在顶层绑定之上:before、after、removed、added。

使用要点

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

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 状态都挂在模块顶层:before、after、removed。

核心语句

const before = new Set(['auth', 'billing', 'search', 'admin']);
const after = new Set(['billing', 'search', 'reports']);

代码示例

const before = new Set(['auth', 'billing', 'search', 'admin']);
const after = new Set(['billing', 'search', 'reports']);

// difference: keys only present in 'before' — candidates to decommission.
const removed = before.difference(after);
console.log('removed:', [...removed]);

// The mirrored call answers the other direction: what was added.
const added = after.difference(before);
console.log('added:', [...added]);

// symmetricDifference: changed on either side — the deploy diff itself.
const changed = before.symmetricDifference(after);
console.log('changed:', [...changed]);

// Cross-check: union minus intersection equals the symmetric difference.
const union = before.union(after);
const shared = before.intersection(after);
console.log('agrees:', [...union.difference(shared)].join() === [...changed].join());