점 연결: 프런트 엔드 및 알고리즘

지난 주에 면접을 봤는데, 다음 주에 현재 React 프로젝트에서 작업할 때 다시 만난 알고리즘 테스트가 있습니다. 순식간에 알아차리고 "케이크 먹듯이"풀었습니다. 이것은 내가 가장 좋아하는 인용문 중 하나를 상기시켜줍니다.



알고리즘 도트 - 병합 간격



자세한 내용은 여기LeetCode에서 확인할 수 있습니다.

예 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].


예 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.




프런트 엔드에 연결



그래서, 제가 지난 주에 본 알고리즘 테스트가 제 현재 작업과 어떻게 관련되어 있는지. 아래 gif를 보자



직접 체험해보세요 ⇒ codesandbox
  • 날짜별로 그룹화된 거래 목록이 있습니다.
  • 처음 로드할 때 몇 가지 항목만 로드합니다.
  • 사용자가 "추가 로드"버튼을 누르면 더 많은 데이터를 가져오기 위해 API를 호출합니다.
  • 데이터가 제공되지만 섹션 날짜 "19.10.2021"에 병합 없이 두 개의 별도 섹션이 표시됩니다.
  • 이제 내 임무는 테마를 함께 병합하는 것입니다. 가자

  • 점들을 잇는



    이것이 해결책입니다

    const merge = (currentList, newList) => {
        // We take the currentList at first load, and the "load more" list.
        // First we just merge it by spread operator => [...currentList, ...newList]
        // After that we use `Array.prototype.reduce` to generate a new array,
        // Which is merged and grouped by date.
      const merged = [...currentList, ...newList].reduce((acc, item) => {
            // Condition 1: just push the item to the new empty array, or
            // if the last item in `acc` doesn't have the same date with the current item
        if (!acc.length || acc[acc.length - 1].date !== item.date) {
          acc.push(item);
        } else {
                // Condition 2: if they have the same date, we merge it. 🤝
          const lastItem = acc[acc.length - 1];
          const mergedDate = [...lastItem.transactions, ...item.transactions];
          lastItem.transactions = mergedDate;
        }
        return acc;
      }, []);
      return merged;
    };
    
    const result = await fakeAPIRequest(page);
    
    setMergedList((prevList) =>
        merge(cloneDeep(prevList), cloneDeep(result.items))
    );
    
    


    그래서 이것은 알고리즘 테스트와 약간 다르지만 아이디어는 동일합니다. 이제 리트코드로 돌아와서 직접 해결해보자.

    알고리즘 테스트는 때때로 악몽이며 실제 프로젝트에서는 거의 생각하거나 사용하지 않기 때문에 종종 과소 평가합니다. 이 경험은 저를 다르게 생각하게 하고 다음 주말에 더 많이 연습하도록 영감을 줍니다.

    좋은 웹페이지 즐겨찾기