具有有效添加/删除操作的唯一对象的列表



我必须在node.js中实现一个订阅列表,目前有这个对象:

var SubReq = function(topic, address, port){
this.topic = topic,
this.address = address,
this.port = port
}
var Subscribers = [];

我还实现了从该列表中添加下标(使用push(和删除下标(使用splice(的功能。下标应该是UNIQUE(只有一个具有相同主题、地址和端口(目前,我使用的是一种非常简单的方法,即扫描整个阵列,检查新订阅是否已经存在,如果不存在,我会添加它。删除也是如此;我必须解析整个数组,直到找到要删除的数组为止。

我的问题是,是否有更好的方法来创建唯一且更有效地添加/删除订阅的列表?

如果有任何帮助,我将不胜感激。谢谢Gus

您可以使用具有唯一键的对象而不是数组。例如

var SubReq = function(topic, address, port){
this.topic = topic,
this.address = address,
this.port = port
}
var topic = "topic1"
var address = "address2"
var port = "port2"
//initialize Subscribers object
var Subscribers = {};
//add a new subscriber
Subscribers[`${topic}-${address}-${port}`] = new SubReq(topic, address, port)
//the result after adding the key
console.log(Subscribers)
//check if the key exists in Subscribers
console.log(`${topic}-${address}-${port}` in Subscribers) 
//delete the key
delete Subscribers[`${topic}-${address}-${port}`]
//the result after deleting the key
console.log(Subscribers)

最新更新