DEV Community

Cover image for Connecting The Dots: Front-end and Algorithms
Trung Nguyen
Trung Nguyen

Posted on • Updated on

Connecting The Dots: Front-end and Algorithms

Last week, I had an interview, there's an algorithm test which I met it again next week when I was working in the current React project. Instantly, I recognized it and solved it "like eat a cake". This just reminds me one of my favorite quotes.

Alt Text

The algorithm dot - Merge Intervals

You can see details here in LeetCode.

Example 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].
Enter fullscreen mode Exit fullscreen mode

Example 2:

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

Alt Text

Connecting to Front-end

So, how this algorithm test I took last week related to my current work. Let's see a gif below

Alt Text

Try it yourself ⇒ codesandbox

  • There's a list transactions grouped by date.
  • At first load, we only load a few items.
  • When users press "Load More" button, we call an api to get more data.
  • Data come but in section date "19.10.2021", without merge we see two separate sections.
  • Now my mission is to merge theme together. Let's go

Connecting The Dots

This is the solution

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))
);

Enter fullscreen mode Exit fullscreen mode

So, this is a little bit different from the algorithm test, but the idea is the same. Now, you can come back to Leetcode and let's solve it by yourself.

Algorithm test is nightmare sometimes, and we often underestimate because in real-life project we barely think or use it. This experience makes me think differently and inspires me to practice more in next weekends.

Top comments (0)