JavaScript
[Lookup Table] 룩업 테이블 (JS Patterns)
눙엉
2022. 1. 27. 02:03
Lookup Table?
자료를 찾아봐도 많은 정보를 얻지 못했다.
짧지만 어떤 느낌인지는 파악할 수 있어서 간단히 적어본다.
사용하는 이유
매번 계산할 필요 없이 저장돼 있는 값을 참조하면 답을 구할 수 있다.
country의 값을 보고 해당하는 나라명을 계산할 때 아래의 함수를 사용할 수 있다.
const getCountry = (country) => {
if ( country === 'us' ) return 'USA';
if ( country === 'jp' ) return 'Japan';
if ( country === 'vn' ) return 'Vietnam';
return 'Korea'
}
물론 switch문을 사용해서도 같은 결과를 얻을 수 있다.
하지만 Object를 사용해서 더 효율적으로 사용할 수 있다.
const country = {
'us' : 'USA',
'jp' : 'Japan',
'vn' : 'Vietnam',
}
const getCountry = (countryName) => country[countryName] || 'Korea';
Object를 사용하게 되면
- 코드가 더 깔끔하고 가독성이 좋아진다.
- if문의 분기처리를 제거하고 간단한 0(1) 조회로 만들 수 있다.
- if문을 끝까지 기다릴 필요없이 Object에 키값이 없으면 바로 기본 값을 반환한다.
참조 : https://omwri.medium.com/javascript-patterns-lookup-tables-26bbaf693e24