프로그래머스 LEVEL 2(오픈 채팅방)
-
사용 언어 : javascript
-
해결 날짜 : 2022-08-13
-
해결 방법 :
- record를 돌며 split()으로 명령어만 따로 추출하여 명령어 별 처리
- 명령어 처리 시 id로 저장 후
- 최종적으로 id를 닉네임으로 변경
-
코드
const result = [];
const users = {};
const commandProcessing = (command) => {
switch(command[0]) {
case 'Enter':
Object.assign(users, {[command[1]]: command[2]});
result.push(`${command[1]}님이 들어왔습니다.`);
break;
case 'Leave':
result.push(`${command[1]}님이 나갔습니다.`);
break;
case 'Change':
users[command[1]] = command[2];
break;
default:
break;
}
}
function solution(record) {
for (const rec of record) {
const command = rec.split(' ');
commandProcessing(command);
}
for (const [index, message] of result.entries()) {
const id = message.split('님')[0];
result[index] = message.replace(id, users[id]);
}
return result;
}