Write a function that turns a list of items into a DOM list.
This is the classic DOM exercise, because it looks easy and it has a dozen small decisions inside it. The interviewer is watching how you build the tree, and not whether you can remember the name of the method that adds a child.
// A tiny stand-in for the browser DOM, so this example runs in Node.
function element(tag, attrs) {
if (!attrs) {
attrs = {};
}
return {
tagName: tag.toUpperCase(),
attributes: attrs,
children: [],
textContent: '',
appendChild: function (child) {
this.children.push(child);
return child;
}
};
}
function renderList(items) {
var list = element('ul', { 'class': 'list' });
for (var i = 0; i < items.length; i++) {
var item = items[i];
var li = element('li', { 'data-id': String(item.id) });
li.textContent = item.label;
list.appendChild(li);
}
return list;
}
var rendered = renderList([
{ id: 1, label: 'Write a spec' },
{ id: 2, label: 'Ship it' }
]);
console.log(rendered.tagName); // UL
console.log(rendered.children.length); // 2
var labels = [];
for (var i = 0; i < rendered.children.length; i++) {
labels.push(rendered.children[i].textContent);
}
console.log(labels); // Write a spec, Ship it
console.log(rendered.children[0].attributes['data-id']); // 1These are the decisions that matter. You build the whole tree before you attach it to the page, so the browser does its layout work once instead of once for every node. You set the text through the textContent property and not through innerHTML, which is safe with any content and does not parse any markup. And you put the identifier in a data attribute, so a click handler can find out which row was clicked without you having to search through the text.
Here is what an interviewer will ask next. What happens with an empty list? The answer is that you either show an empty state message or leave the list empty, and you decide which one you want. How would you update the list when the data changes? The answer is that you render it again and replace the children, or that you compare the old list with the new one if the list is long. And how would you test it? That is where a function that takes data and returns an element is far easier to test than a function that reaches into the page by itself.