Re: Dustin’s Brain Teaser

I’m a bit late, but rather later then never :). I just didn’t had even 10 Minutes spare time in the last few days.

Here is my response to Dustin’s brain teaser. I’m offering a solution without regular expressions. Though after reading the problem I first thought “Nice, I’ll use regular expressions.”. But then I realized that now I’m facing two problems :). I’m really not that good at regexps.
But I promise I’ll keep the teaser in mind and one day I’ll solve it with regular expressions.

var teaserNoRegExp = function() {
  var input = ['a', 'b', 'c', 'c', 'd','e', 'e','e', 'e',
'e', 'f', 'e', 'f', 'e','f', 'a', 'a', 'a', 'f', 'f', 'f'];
  var output = '';

  // assume Array.prototype.forEach

  var spanOpened = false;
  input.forEach(function(el, index, input){
    if (input[index-1] == el && input[index-2] == el && !spanOpened) {
      output = output + '';
      spanOpened = true;
    }
    output = output + ' ' + el;
    if (input[index+1] != el && spanOpened) {
      output = output + '';
      spanOpened = false;
    }
  });
  document.getElementById('result').value = output;
};

P.S. It actually took me a minute or two to write it down.

Tags: , ,

Leave a Reply