function Chat() {
// do your magic
let users = new Map();
function login(id) {
if (!users.has(id)) {
users.set(id, { online: true, loginCount: 1 });
} else if (!users.get(id).online) {
users.get(id).online = true;
users.get(id).loginCount += 1;
}
}
function logout(id) {
if (users.has(id) && users.get(id).online) users.get(id).online = false;
}
function isOnline(id) {
return users.has(id) && users.get(id).online;
}
function countOnline() {
let count = 0;
users.forEach((user) => {
if (user.online) count++;
});
return count;
}
function countLogins(id) {
return users.has(id) ? users.get(id).loginCount : 0;
}
return {
login,
logout,
isOnline,
countOnline,
countLogins,
};
}
const myChat = Chat();
myChat.login(3);
myChat.login(2);
myChat.logout(3);
console.log(myChat.countOnline()); // 1
ZnVuY3Rpb24gQ2hhdCgpIHsKICAvLyBkbyB5b3VyIG1hZ2ljCiAgbGV0IHVzZXJzID0gbmV3IE1hcCgpOwoKICBmdW5jdGlvbiBsb2dpbihpZCkgewogICAgaWYgKCF1c2Vycy5oYXMoaWQpKSB7CiAgICAgIHVzZXJzLnNldChpZCwgeyBvbmxpbmU6IHRydWUsIGxvZ2luQ291bnQ6IDEgfSk7CiAgICB9IGVsc2UgaWYgKCF1c2Vycy5nZXQoaWQpLm9ubGluZSkgewogICAgICB1c2Vycy5nZXQoaWQpLm9ubGluZSA9IHRydWU7CiAgICAgIHVzZXJzLmdldChpZCkubG9naW5Db3VudCArPSAxOwogICAgfQogIH0KCiAgZnVuY3Rpb24gbG9nb3V0KGlkKSB7CiAgICBpZiAodXNlcnMuaGFzKGlkKSAmJiB1c2Vycy5nZXQoaWQpLm9ubGluZSkgdXNlcnMuZ2V0KGlkKS5vbmxpbmUgPSBmYWxzZTsKICB9CgogIGZ1bmN0aW9uIGlzT25saW5lKGlkKSB7CiAgICByZXR1cm4gdXNlcnMuaGFzKGlkKSAmJiB1c2Vycy5nZXQoaWQpLm9ubGluZTsKICB9CgogIGZ1bmN0aW9uIGNvdW50T25saW5lKCkgewogICAgbGV0IGNvdW50ID0gMDsKICAgIHVzZXJzLmZvckVhY2goKHVzZXIp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