Dustin Diaz’s Brain Teaser

Late last night Dustin Diaz posted a short brain teaser, there are lots of solutions already posted, but I didn’t see any with a similar approach to mine, so I thought I would also share:

  1.             var arr = ['a', 'b', 'c', 'c', 'd', 'e', 'e',
  2.                        'e', 'e', 'e', 'f', 'e', 'f', 'e',
  3.                        'f', 'a', 'a', 'a', 'f', 'f', 'f'];
  4.  
  5.             var output  = [];
  6.             var tracker = [];
  7.  
  8.             arr.forEach(function(item, index, ar) {
  9.  
  10.                 // check if the tracker array matches the current item
  11.                 if( tracker[0] === item ){
  12.                     // then check if we need to insert a marker
  13.                     if( tracker.length == 2 ){
  14.                          output[output.length] = '<span>';
  15.                     }
  16.                 }
  17.                 else {
  18.                     // if it is different check if we need to close the marker
  19.                     if(tracker.length > 2){
  20.                         output[output.length] = '</span>';
  21.                     }
  22.  
  23.                     // now reset the tracking array
  24.                     tracker = [];
  25.                 }
  26.  
  27.                 // add to the tracking and output arrays
  28.                 tracker[tracker.length] = item;
  29.                 output[output.length] = item;
  30.  
  31.                 // close up, just incase we are open
  32.                 if( index == ar.length - 1  && tracker.length > 2){
  33.                    output[output.length] = '<span>';
  34.                 }
  35.  
  36.             });
  37.  
  38.            document.write(output.join(''));

and here is my live demo.

Sorry, comments for this entry are closed at this time.