알고리즘을 풀며 객체에 배열을 저장하고 이를 늘려갈 때 나는 concat을 자주 사용했다.
if 문을 이용하여 객체에 해당 키가 있는지 유무를 확인하지 않고 바로 한 줄에 끝내 버릴 수 있었기 때문이다.
하지만 오늘 이 부분에 대해 갑자기 생각하게 되었다. 사람들은 왜 굳이 if 문을 사용할까?
이에 대해 내가 너무 얕게 고민하고 push가 아닌 concat을 사용했다는 것을 알게 되어 이 차이점을 정리해 봤다.
장점
단점
function groupAnagrams(words) {
const results = {};
for (const word of words) {
const sortedWord = [...word].sort().join("");
results[sortedWord] = (results[sortedWord] || []).concat(word);
}
return Object.values(results);
}
장점
단점?
function groupAnagrams(words) {
const results = {};
for (const word of words) {
const sortedWord = [...word].sort().join("");
if (results[sortedWord]) {
results[sortedWord].push(word);
} else {
results[sortedWord] = [word];
}
}
return Object.values(results);
}
💬
지금은 이렇게 하나하나 생각하며 사용해야 하지만 나중에는 자연스럽게 작성해도 알맞은 코드를 작성하게 되겠지?!! 그때는 또 어떤 고민들을 할까 기대가 된다!!