js实现集合
set是集合
集合是由一组无序且唯一(即不能重复)的项组成的。该数据结构使用了与有限集合相同的数学概念,但应用在计算机科学的数据结构中
构建set
1 class set{ 2 constructor(){ 3 this.items = {} 4 } 5 has(element){ 6 return element in this.items 7 // Object 原型有 hasOwnProperty 方法。该方法返回一个表明对象是否具有特定属性的布尔值 8 // return Object.prototype.hasOwnProperty.call(this.items, element) 9 } 10 add(element){ 11 if (!this.has(element)) { 12 this.items[element] = element 13 return true 14 } 15 return false 16 } 17 delete(element){ 18 if(this.has(element)){ 19 delete this.items[element] 20 return true 21 } 22 return false 23 } 24 clear(){ 25 this.items = {} 26 } 27 size(){ 28 // JavaScript 的 Object 类有一个 keys 方法,它返回一个包含给定对象所有属性的数组 29 return Object.keys(this.items).length 30 } 31 values(){ 32 // Object.values()方法返回了一个包含给定对象所有属性值的数组 33 return Object.values(this.items) 34 } 35 union(otherSet){ 36 // 取当前集合和新集合的并集 37 const unionSet = new set() 38 this.values().forEach(value => unionSet.add(value)) 39 otherSet.values().forEach(value => unionSet.add(value)) 40 return unionSet 41 } 42 intersection(otherSet){ 43 // 交集 44 const intersectionSet = new set() 45 const ownValue = this.values() 46 const otherValue = otherSet.values() 47 ownValue.forEach(value => { 48 if(value in otherValue){ 49 intersectionSet.add(value) 50 } 51 }) 52 return intersectionSet 53 } 54 difference(otherSet){ 55 // 差集,存在于当前集合但不存在于新集合中 56 const differenceSet = new set() 57 const ownValue = this.values() 58 const otherValue = otherSet.values() 59 ownValue.forEach(value => { 60 if(!(value in otherValue)){ 61 differenceSet.add(value) 62 } 63 }) 64 return differenceSet 65 } 66 isSubsetOf(otherSet){ 67 // 当前集合是否是其他集合的子集 68 if(this.size() > otherSet.size()){ 69 return false 70 } 71 let isSubset = true // 返回值 72 const ownValue = this.values() 73 const otherValue = otherSet.values() 74 ownValue.forEach(value => { 75 if(!(value in otherValue || this.size() === 0)){ 76 isSubset = false 77 } 78 }) 79 return isSubset 80 } 81 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器