Set Union And Intersection Methods

Compute set algebra with the ES2025 Set methods union, intersection, difference, and symmetricDifference, plus isSubsetOf and isDisjointFrom relation checks.

TypescriptData Integrity

Code

typescriptsnippet
18 lines
// 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'])));

Output

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

union: delete,publish,read,write
intersection: read,write
difference: delete
subset: false
disjoint: true

Inside the snippet

Top-level bindings adminPerms, editorPerms, all, shared hold the demo state — nothing sits inside a function scope.

Putting it to use

The demo output is labeled (union:, intersection:, difference:), so each line of output maps back to the operation it came from.

Core lines

const editorPerms = new Set(['read', 'write', 'publish']);
const adminPerms = new Set(['read', 'write', 'delete']);

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `adminPerms`, `editorPerms`, `all`.