object-literal-lookup 는 Javascript 에서 객체를 사용하여 switch 문을 대체하는 방법입니다.
객체를 사용하면 조건을 키-값 쌍으로 정리하여 가독성을 높이고 유지보수를 쉽게 할 수 있습니다.
동물 의 소리를 출력하는 switch 문을 예로 들어보겠습니다.
function animalSound(animal) {
switch (animal) {
case 'dog':
return '멍멍';
case 'cat':
return '야옹';
case 'cow':
return '음매';
default:
return '알 수 없는 동물입니다.';
}
}
console.log(animalSound('dog')); // 멍멍
console.log(animalSound('cat')); // 야옹
이 코드를 object-literal-lookup으로 리팩토링 하면 다음과 같습니다.
const animalSounds = {
dog: '멍멍',
cat: '야옹',
cow: '음매',
};
function animalSound(animal) {
return animalSounds[animal] || '알 수 없는 동물입니다.';
}
console.log(animalSound('dog')); // 멍멍
console.log(animalSound('cat')); // 야옹
switch 문 대신 객체를 사용하여 코드가 더 깔끔해졌죠?
우리코드에도 적용해볼까요?
const APIS = {
...useDeviceSystem(),
...useDeviceLocation(),
};
const onResponse = (result) => {
webviewRef.current?.postMessage(JSON.stringify(result));
};
const onRequest = async (query) => {
const result = await APIS[query]();
onResponse(result);
};