프로그래머스: 오픈 채팅방

공룡개발자·2022년 3월 26일
1



✍ 나의 풀이

function solution(record) {
    const users = {}
    const orders = []
    for(let rec of record){
        const [action, username, nickname = '' ] = rec.split(' ')
        if(action === 'Enter'){
            users[username] = nickname;
            orders.push([action, username]);
        } else if(action === 'Leave'){
            orders.push([action, username]);
        } else {
            users[username] = nickname;
        }
    }

    const result = []
    for(let rec of orders){
        const [action, username] = rec
        if(action === "Enter"){
            result.push(`${users[username]}님이 들어왔습니다.` )
        } else {
            result.push(`${users[username]}님이 나갔습니다.` )
        }
    }

    return result
}

✍ 풀이과정

  1. user의 최종 닉네임을 저장하기 위한 users 객체 선언
  2. user의 행동을 기록할 orders 배열 선언
  3. const [action, username, nickname = '' ] = rec.split(' ')
    'Leave' 행동에 대해서는 nickname 요소가 없어 디폴트값 할당
  4. users[username] = nickname;
    해당 username이라는 key가 없을 때는 추가해주고, key가 있을 때는 업데이트해주는 방식

✍ 중복 제거

function solution(record) {
    const users = {}
    const orders = []
    const text = {
        Enter: '님이 들어왔습니다.',
        Leave: '님이 나갔습니다.',
    }
    
    for(let rec of record){
        const [action, username, nickname = '' ] = rec.split(' ')
        if(action !== 'Change') orders.push([action, username]);
        if(nickname) users[username] = nickname;
    }
    
    return orders.map(v => users[v[1]] + text[v[0]])
}

✍ 학습요망

https://kis6473.tistory.com/167

profile
공룡의 발자취

0개의 댓글