프로그래머스 [신고 결과 받기] 리팩토링

JH.P·2022년 9월 23일
  • 2월 5일에 카카오 코테 기출 중 "신고 결과 받기" 라는 문제를 풀었었다.
  • 지금 다시 보니 코드가 굉장히 지저분하고 장황하더라..
  • 비록 완벽까진 아니겠지만, 코드를 아래와 같이 개선하였다.
function solution(id_list, report, k) {
    // 정답 배열
    let answer = Array(id_list.length).fill(0)
    
    // 신고당한사람과 신고한사람 분리
     report = report.map(item => item.split(' '))
   
    // 신고당한사람 : [신고한사람, 신고한사람, ...] 만들기
    const reportMap = new Map()
    
    for(let i = 0; i < report.length; i++) {
        const data = reportMap.get(report[i][1]) || []
        if(!data.includes(report[i][0])) {
              reportMap.set(report[i][1], [...data, report[i][0]])    
        }
      
    }
    
    // 정지되는 사람 남기기
    let reportArr = [...reportMap].filter(item => item[1].length >= k)
    
    // 신고한 사람들 쭉 순회하며 id_list와 대조시켜 신고한 사람 1씩 증가
    reportArr = reportArr.flatMap(item => item).filter(item => typeof item === 'object').flatMap(item => item)
    
    reportArr.forEach(item => {
        const index = id_list.indexOf(item)
        answer[index] += 1
    })
    
    return answer
}
profile
꾸준한 기록

0개의 댓글