본문 바로가기
클린코드

Lookup Table

by Nhahan 2022. 9. 5.

if - else if - else를 switch로 리팩토링하는 케이스는 엄청 흔하다.

function getChannelType(channelType) {
    switch(channelType) {
    	case "A":
        	return "A 채널";
    	case "B":
        	return "B 채널";
    	case "C":
        	return "C 채널";
        default:
        	return "채널 없음";
    }
}

 

근데 이걸 이렇게도 할 수 있다.

function getChannelType(channelType) {
    const CHANNEL_TPYE = {
    	A: 'A 채널',
        B: 'B 채널',
        C: 'C 채널',
    };
    return CHANNEL_TYPE[channeltype] || '채널 없음';
}

case와 return문이 한 줄에 간략하게 표현되서 알아보기 쉬워졌다.

 

 

사실 case문도 나쁘다는 생각은 하지 않지만, 룩업 테이블의 진가는 case가 2개 이상의 property를 가진 객체일 때 발휘된다.

 

 

댓글