DEV Community

Zhenghao He
Zhenghao He

Posted on

Reordering elements on an HTML form using Vanila JS: what's the best practice in terms of performance?

I got this take home assignment last year when I was applying for a front end engineer position at some big Japanese company.

The question is about making a form with a button to make table rows randomly rearrange every second, and a button to sort rows based on some criteria. The way I rearrange the rows in the form is to manipulating the JSON object and regenerate the dom element as a whole

This has to be implemented via pure JS without using any JS libraries.

I put the code on codesandbox, here is the link
https://codesandbox.io/s/dawn-water-l2m7g

Basically the way I rearrange the rows in the form is to manipulating the JSON object and regenerate the DOM element as a whole.

Here is an important piece from my code

let list = TABLE_DATA; // from the JSON file
...

function startRandom() {
  timer = setInterval(function() {
    list = list.sort(randomSort);
    renderList(list);
  }, 1000);
}

function renderList(list) {
  const res = list
    .map(item => {
      return renderRow(xssFilter(item));
    })
    .join("");

  tbody.innerHTML = res;
}

function renderRow(item) {
  return `
    <tr>
        <td>${item.id}</td>
        <td><img src="${item.thumbnailUrl}" /></td>
        <td>${item.name}</td>
        <td>${item.price}</td>
    </tr>
    `;
}

The form worked. And I fulfilled the two functionalities i.e. shuffle and sort. However I didn't pass the first round. Because they also asked to think about the performance and avoid any unnecessary reflow and repaint. So I guess the reason I got rejected was because my stuff wasn't great performance-wise. Every time renderList is invoked, the whole tbody is going to be destroyed and recreated again.

I hope someone can take a look at it and make some optimizations based on the functionalities it has now. Even though I ended up working at some other big company here in Canada, to this date I'm still wondering how this could be improved.

Top comments (0)