JSFiddle - React, Tailwind, and code Playground

by RubenVerborgh

HTML

<pre id="results"></pre>

JavaScript

/***** TWO IMPLEMENTATIONS *****/

function representFeaturedLabelsQuick (labels) {
  // Remember smallest and second-smallest indices
  var firstIndex = -1, secondIndex = -1;
  var html = "";
  for (var i = 0; i < labels.length; i++) {
    // Is this label smaller than the current second-smallest?
    if (secondIndex == -1 || labels[i] < labels[secondIndex]) {
      // Is this label also smaller than the current smallest?
      if (firstIndex == -1 || labels[i] < labels[firstIndex]) {
        // This label is the smallest, so (re-)represent
        html = "<div><span>" + labels[i] + "</span> <span>" +
               labels[secondIndex] + "</span></div>";
        firstIndex = i;
      }
      else {
        // Replace the current second-smallest label
        html = html.replace(labels[secondIndex], labels[i]);
        secondIndex = i;
      }
    }
  }
  return html;
}

function representFeaturedLabelsElegant (labels) {
  // Find the alphabetically first two labels
  var featured = labels.sort().slice(0, 2);
  // Return a <div> containing the first labels
  return "<div><span>" + featured.join("</span> <span>") +
         "</span></div>";
}


/***** TEST CASES *****/

test(["Anna", "Carl", "Bert"]);
test(["Bert", "Carl", "Anna"]);
test(["Carl"]);


/***** TEST UTILS *****/

function test (elements) {
  show("Represent first two of", elements.join(", "));
  show(" - quick:  ", representFeaturedLabelsQuick(elements));
  show(" - elegant:", representFeaturedLabelsElegant(elements));
  show();
}
function show() {
  var results = document.getElementById("results");
  results.innerText += Array.prototype.join.call(arguments, " ") + "\n";
}