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 expectedif(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?