Created
May 23, 2020 22:29
-
-
Save kenduigraha/dece93048fbf11a7e7032e10835bb8a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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