Set Methods Compute Union And Intersection
Compare sets with the ES2024 methods union, intersection, difference, symmetricDifference, isSubsetOf, and isDisjointFrom — every call returns a new Set.
Code
// ES2024 Set 方法:每个运算都返回全新的 Set,可以继续链式组合
const staging = new Set(['api', 'web', 'worker', 'billing']);
const prod = new Set(['api', 'web', 'email']);
const sort = (s) => [...s].sort();
console.log('union :', sort(staging.union(prod)));
console.log('shared :', sort(staging.intersection(prod)));
console.log('staging only:', sort(staging.difference(prod)));
console.log('symmetric :', sort(staging.symmetricDifference(prod)));
// 关系判断直接回答发布问题:能不能整体晋升、两个环境是否完全隔离
console.log('prod subset of staging?', prod.isSubsetOf(staging));
console.log('disjoint from coldstorage?', staging.isDisjointFrom(new Set(['coldstorage'])));
// 返回值仍是 Set:先取两环境共有的服务,再并入待引入的 cdn
console.log('promote-ready:', sort(staging.intersection(prod).union(new Set(['cdn']))));Output
Captured from a sandboxed run of this snippet in the build pipeline.
union : [ 'api', 'billing', 'email', 'web', 'worker' ]
shared : [ 'api', 'web' ]
staging only: [ 'billing', 'worker' ]
symmetric : [ 'billing', 'email', 'worker' ]
prod subset of staging? false
disjoint from coldstorage? true
promote-ready: [ 'api', 'cdn', 'web' ]How the snippet works
Set Methods Compute Union And Intersection reduces to the function sort.
Using it
Entry signature: const sort = (s)
The demo output is labeled (staging only:, prod subset of staging?, disjoint from coldstorage?), so every printed line maps back to its originating operation.
Key statements
const sort = (s) => [...s].sort();
const staging = new Set(['api', 'web', 'worker', 'billing']);
const prod = new Set(['api', 'web', 'email']);
Interactive Tools for This Topic
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `sort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.