Programming Brain Teaser

Tue, 08 Jul 2008

Dustin Diaz put an interesting task on his blog. In short, you have an array:

var arr = ["a", "b", "c", "c", "d", "e", "e", "e", "e", "e",
"f", "e", "f", "e", "f", "a", "a", "a", "f", "f", "f"];

and it should be turned into string like this:

"a b c c d e e <span>e e e</span> f e f e f a a <span>a</span> f f
<span>f</span>"

First solution in my mind is this:

alert(arr.join(" ").replace(/([a-z])\s\1\s((\1\s?)+)(?=\s|$)/g,
"$1 $1 <span>$2</span>"));

But I feel like a cheater, probably I missed some limitation in the task. Will submit it and wait for comments from Dustin. In case I got it wrong, I will update the post.

Update

Just in case I have to use forEach function:

var arr = ["a", "b", "c", "c", "d", "e", "e", "e", "e",
           "e", "f", "e", "f", "e", "f", "a", "a", "a", "f", "f", "f"];
Array.prototype.forEach = function (f) {
    for (var i = 0, ii = this.length; i < ii; i++) {
        f(this[i], i, this);
    }
};


var res = "", isTag = false;
arr.forEach(function (item, index, ar) {
    if (!isTag && ar[index - 1] == ar[index - 2] && ar[index - 2] == item) {
        res += "<span>";
        isTag = true;
    }
    res += item;
    if (isTag && ar[index + 1] && ar[index + 1] != item) {
        res += "</span>";
        isTag = false;
    }
    if (ar[index + 1]) {
        res += " ";
    } else if (isTag) {
        res += "</span>";
    }
});
console.log(res);