1회차 코드 리뷰 스터디 #3
Replies: 4 comments
-
|
뭔가 쉬우면서 어렵네요 ㅋㅋㅋ
제가 만-약 수정해본다면 nonExistingIds와 map하는 연산을 reduce로 한 번에 묶어볼 것 같습니다 newIds.reduce<(StateItem | null)[]>((acc, id) => {
const existingItem = original.find(item => item?.id === id);
if (existingItem) {
acc.push(existingItem);
} else {
acc.push({ id, isRead: false });
}
return acc;
}, []); |
Beta Was this translation helpful? Give feedback.
-
return original
.map((item) => (item && newIds.includes(item.id) ? item : null))
.map((item) =>
item
? item
: nonExistingIds.length > 0
? { id: nonExistingIds.shift()!, isRead: false }
: null,
);이 코드가 map이 이중으로 존재하는데, 가독성이 좋지는 않아보여서 첫번째 요런 너낌으로다가? const updatedArray = original.map(item =>
item && newIds.includes(item.id) ? item : null
);
return updatedArray.map( //.. |
Beta Was this translation helpful? Give feedback.
-
|
뭔가 알고리즘 문제 느낌이네용!! 저는 js로 알고리즘 문제를 풀 때 map을 여러 개 쓰기보다는 reduce를 애용했었습니다!! 예외 처리할 때 더 직관적으로 찾을 수 있더라구요!! (이미 재한님이 의견을 주셨군요,,,) |
Beta Was this translation helpful? Give feedback.
-
아래는 GPT 의 의견인데, Set 을 사용하면 특정값의 존재 여부를 훨씬 빨리 사용할 수 있다고 해요. 저도 처음 안 내용이라 적어두고 갑니다. Set 을 사용하는 이유
GPT 의 의견 ) const syncArrayWithNewIds = (
original: (StateItem | null)[],
newIds: number[],
) => {
// original 배열에서 존재하는 id들을 Set으로 저장하여 빠르게 조회할 수 있도록 합니다.
const existingIdsSet = new Set(original.filter(item => item).map(item => item!.id));
// newIds 배열에서 original에 없는 id들을 필터링하여 저장합니다.
const nonExistingIds = newIds.filter(id => !existingIdsSet.has(id));
// original 배열을 순회하면서 필요한 변환을 수행합니다.
return original.map(item => {
// item이 존재하고 newIds에 포함되어 있으면 그대로 유지합니다.
if (item && newIds.includes(item.id)) {
return item;
}
// 그렇지 않으면 nonExistingIds에서 id를 하나 꺼내 새로운 객체를 생성합니다.
if (nonExistingIds.length > 0) {
return { id: nonExistingIds.shift()!, isRead: false };
}
// nonExistingIds가 비어있으면 null을 반환합니다.
return null;
});
}; |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
이전에 구현했던 로직이 꽤나 복잡하게 느껴졌었어요.
혹시 간단하게 해결할 수 있는 방법이 있을지, 함께 고민해보면 좋을 것 같아서 코드를 가져왔어요. 😊
구현 기능
문제 상황
해결 방법
Beta Was this translation helpful? Give feedback.
All reactions