实现说明
adminPerms、editorPerms、all、shared 定义在模块顶层,中间不经过函数作用域。
使用要点
- 直接运行文件,输出会带上标签,比如
union:、intersection:、difference:——输出的每一行都能指回产生它的那次调用。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 文件用顶层绑定保存自己的状态:adminPerms、editorPerms、all。
核心语句
const editorPerms = new Set(['read', 'write', 'publish']);
const adminPerms = new Set(['read', 'write', 'delete']);
代码示例
// ES2025 Set methods: 集合运算不再需要手写循环
const adminPerms = new Set(['read', 'write', 'delete']);
const editorPerms = new Set(['read', 'write', 'publish']);
// 并集:两个角色的全部权限
const all = adminPerms.union(editorPerms);
console.log('union:', [...all].sort().join(','));
// 交集:两边同时持有的权限
const shared = adminPerms.intersection(editorPerms);
console.log('intersection:', [...shared].sort().join(','));
// 差集:admin 有而 editor 没有
console.log('difference:', [...adminPerms.difference(editorPerms)].sort().join(','));
// 子集与不相交判断
console.log('subset:', editorPerms.isSubsetOf(adminPerms));
console.log('disjoint:', editorPerms.isDisjointFrom(new Set(['delete'])));