I am building a simple chat system and I have a function that will broadcast to all clients the list of online users.
This is working well but I run this function every minute and it sends the list back even if nothing has changed. I am trying to implement a check to see if the list has changed compared to previous iteration but I am stuck finding a way to perform the comparison.
My first attempt was the following:
var oldUsersList = { type: 'onlineusers', users: [] };
// Update online users list, specially if someone closed the chat window.
function updateOnlineUsers() {
const message = { type: 'onlineusers', users: [] };
// Create a list of all users.
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
message.users.push({ id: client.id, text: client.username, date: client.date });
}
});
console.log(oldUsersList);
console.log('message '+message);
if(oldUsersList.users==message.users){
console.log('match');
}else{
oldUsersList=message;
// Send the list to all users.
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
}
}
but i face two different issues:
-
console.log(oldUsersList);
will echo{ type: 'onlineusers', users: [] };
and to me it looks like js is considering it as a string whileconsole.log('message '+message);
will echo[object Object]
as expected -
if(oldUsersList.users==message.users)
will never return true even if the two are equals.
What is the right way to check if the list of users have changed?
3
Answers
After digging into
Set
as suggested by @Barmar I ended up usingJson.stringify()
because onSet
comparison I haven't found a working solution to find an exact match between the two list but only solution where you check one list against another and this will provide a wrong result to me if the list to compare against have more users then the new oneThe caveat for this solution is that the keys must be in the same order (in my situation they are always). If so you can just do:
and this returns true if the two lists contains the same users.
You have a realtime list of online users that updating after change?
If currect you can get stringify all user id like this:
1,2,4,22,55,77
After get convert to array of number, then use foreach for current user list to apply changes.for example:
here’s the array implementation
it checks if all the members of new user IDs are present in the Old user IDs
in this way if the new user has joined the list of newUserIDs, doesOldUserListChanged will be true.
if members of the list exit the chat you can use the following as well