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).isOnline) users.get(id).isOnline = false;
}
function isOnline(id) {
return users.has(id) && users.get(id).isOnline;
}
function countOnline() {
let c = 0;
users.forEach((user) => {
if (user.isOnline) c++;
});
return c;
}
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
ZnVuY3Rpb24gQ2hhdCgpIHsKICAvLyBkbyB5b3VyIG1hZ2ljCiAgbGV0IHVzZXJzID0gbmV3IE1hcCgpOwoKICBmdW5jdGlvbiBsb2dpbihpZCkgewogICAgaWYgKCF1c2Vycy5oYXMoaWQpKSB7CiAgICAgIHVzZXJzLnNldChpZCwgeyBvbmxpbmU6IHRydWUsIGxvZ2luQ291bnQ6IDEgfSk7CiAgICB9IGVsc2UgaWYgKCF1c2Vycy5nZXQoaWQpLm9ubGluZSkgewogICAgICB1c2Vycy5nZXQoaWQpLm9ubGluZSA9IHRydWU7CiAgICAgIHVzZXJzLmdldChpZCkubG9naW5Db3VudCArPSAxOwogICAgfQogIH0KCiAgZnVuY3Rpb24gbG9nb3V0KGlkKSB7CiAgICBpZiAodXNlcnMuaGFzKGlkKSAmJiB1c2Vycy5nZXQoaWQpLmlzT25saW5lKSB1c2Vycy5nZXQoaWQpLmlzT25saW5lID0gZmFsc2U7CiAgfQoKICBmdW5jdGlvbiBpc09ubGluZShpZCkgewogICAgcmV0dXJuIHVzZXJzLmhhcyhpZCkgJiYgdXNlcnMuZ2V0KGlkKS5pc09ubGluZTsKICB9CgogIGZ1bmN0aW9uIGNvdW50T25saW5lKCkgewogICAgbGV0IGMgPSAwOwogICAgdXNlcnMuZm9yRWFjaCgodXNlcikgPT4gewogICAgICBpZiAodXNlci5pc09ubGluZSkgYysrOwogICAgfSk7CiAgICByZXR1cm4gYzsKICB9CgogIGZ1bmN0aW9uIGNvdW50TG9naW5zKGlkKSB7CiAgICByZXR1cm4gdXNlcnMuaGFzKGlkKSA/IHVzZXJzLmdldChpZCkubG9naW5Db3VudCA6IDA7CiAgfQoKICByZXR1cm4gewogICAgbG9naW4sCiAgICBsb2dvdXQsCiAgICBpc09ubGluZSwKICAgIGNvdW50T25saW5lLAogICAgY291bnRMb2dpbnMsCiAgfTsKfQoKY29uc3QgbXlDaGF0ID0gQ2hhdCgpOwpteUNoYXQubG9naW4oMyk7Cm15Q2hhdC5sb2dpbigyKTsKbXlDaGF0LmxvZ291dCgzKTsKY29uc29sZS5sb2cobXlDaGF0LmNvdW50T25saW5lKCkpOyAvLyAxCg==