I have to implement a subscriptions list in node.js and currently have this object:
var SubReq = function(topic, address, port){
this.topic = topic,
this.address = address,
this.port = port
}
var Subscribers = [];
I also implemented functions to add subscriptors (using push) and delete subscriptors (using splice) from that list. The subscriptos should be UNIQUE (only one with same topic, address, and port) At the moment I'm using a very simple approach which consist on scanning the whole array to check if the new subscription exist already, and if it doesn't, I add it. Same with delete; I have to parse the whole array until I find the one to delete.
My question is if there is a better approach to create lists that are unique and more efficient to add/delete subscriptions?
I would appreciate any help. Thanks Gus
CodePudding user response:
You can use an object with unique keys instead of an array. For example
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)