如何在TypeScript中实现唯一值对集合?
TypeScript 实现唯一值对集合的可行方案
针对你需要的「值对组合唯一、支持添加和存在性检查」的需求,这里提供几种实用的实现方案:
方案1:将值对序列化为唯一字符串存入 Set
原生 Set 对引用类型按引用比较,但对字符串是按值比较。我们可以把两个值拼接成唯一字符串作为 Set 的元素,避开引用比较的问题。
const pairSet = new Set<string>(); // 添加值对 function addPair(a: string | number, b: string | number) { // 用空字符(\u0000)作为分隔符,避免和业务值冲突;若值可能包含任意字符,可改用 JSON.stringify([a, b]) const key = `${a}\u0000${b}`; pairSet.add(key); } // 检查值对是否存在 function hasPair(a: string | number, b: string | number) { const key = `${a}\u0000${b}`; return pairSet.has(key); } // 使用示例 addPair('a', 'k'); addPair('a', 'm'); console.log(hasPair('a', 'k')); // true console.log(hasPair('a', 'p')); // false
优缺点:实现极简,性能优异;需确保分隔符不会与值内容冲突,用 JSON.stringify 则更安全但性能略降。
方案2:使用嵌套 Map + Set 结构
用外层 Map 存储第一个值,对应的值是一个 Set,专门存储与该值配对的所有第二个值,实现精准的存在性判断。
const pairMap = new Map<string | number, Set<string | number>>(); function addPair(a: string | number, b: string | number) { if (!pairMap.has(a)) { pairMap.set(a, new Set()); } pairMap.get(a)!.add(b); } function hasPair(a: string | number, b: string | number) { const secondSet = pairMap.get(a); return secondSet ? secondSet.has(b) : false; } // 使用示例 addPair('b', 'm'); addPair('b', 'n'); console.log(hasPair('b', 'n')); // true console.log(hasPair('b', 'p')); // false
优缺点:添加和查询效率高,还能方便扩展「查询某个值对应的所有配对值」的功能;结构比字符串方案稍复杂,但逻辑清晰。
方案3:自定义封装类(推荐)
把上述实现封装成类,对外提供简洁的 API,隐藏内部细节,更符合工程化复用的需求。
class UniquePairSet { private storage = new Map<string | number, Set<string | number>>(); // 添加值对(重复添加无效果) add(a: string | number, b: string | number): void { if (!this.storage.has(a)) { this.storage.set(a, new Set()); } this.storage.get(a)!.add(b); } // 检查值对是否存在 has(a: string | number, b: string | number): boolean { const secondSet = this.storage.get(a); return secondSet?.has(b) ?? false; } // 可选:添加删除值对的方法 delete(a: string | number, b: string | number): boolean { const secondSet = this.storage.get(a); if (!secondSet) return false; const result = secondSet.delete(b); // 若第一个值对应的配对集合为空,清理外层Map的键 if (secondSet.size === 0) { this.storage.delete(a); } return result; } } // 使用示例 const pairSet = new UniquePairSet(); pairSet.add('a', 'k'); pairSet.add('a', 'k'); // 重复添加无效果 console.log(pairSet.has('a', 'k')); // true console.log(pairSet.has('a', 'x')); // false
优缺点:API 友好,使用简单,可扩展性强(比如添加遍历、批量操作等方法);适合作为项目中的通用工具类。
内容的提问来源于stack exchange,提问作者timbre timbre
相关产品推荐
相关产品推荐

