Skip to content

Instantly share code, notes, and snippets.

@kenduigraha
Created May 23, 2020 22:29
Show Gist options
  • Save kenduigraha/dece93048fbf11a7e7032e10835bb8a5 to your computer and use it in GitHub Desktop.
Save kenduigraha/dece93048fbf11a7e7032e10835bb8a5 to your computer and use it in GitHub Desktop.
let solution = (record) => {
let answer = [];
let userChat = [];
for (let i = 0; i < record.length; i++) {
let command = record[i].split(" ")[0];
let userId = record[i].split(" ")[1];
let nickName = record[i].split(" ")[2];
let checkExistingUser = userChat
.map((data, index) => (data.userId === userId ? index : ""))
.filter(String);
let newData = {
command,
userId,
nickName,
};
switch (command) {
case "Leave":
userChat.push({
...userChat[checkExistingUser],
command,
});
break;
case "Enter":
case "Change":
if (checkExistingUser.length >= 0) {
// replace the nickName & existing data
checkExistingUser.map((existingIndex) => {
userChat[existingIndex] = {
...userChat[existingIndex],
nickName: newData.nickName,
};
});
}
userChat.push(newData);
break;
}
}
userChat.map((finalData) => {
const { nickName, command } = finalData;
if (command === "Enter") {
answer.push(nickName + " came in.");
}
if (command === "Leave") {
answer.push(nickName + " has left.");
}
});
return answer;
};
let record = [
"Enter uid1234 Muzi",
"Enter uid4567 Prodo",
"Leave uid1234",
"Enter uid1234 Prodo",
"Change uid4567 Ryan",
];
// answer:
// ["Prodo came in.", "Ryan came in.",
// "Prodo has left.", "Prodo came in."]
console.log(solution(record));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment