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:
-
var arr = ['a', 'b', 'c', 'c', 'd', 'e', 'e',
-
'e', 'e', 'e', 'f', 'e', 'f', 'e',
-
'f', 'a', 'a', 'a', 'f', 'f', 'f'];
-
-
var output = [];
-
var tracker = [];
-
-
arr.forEach(function(item, index, ar) {
-
-
// check if the tracker array matches the current item
-
if( tracker[0] === item ){
-
// then check if we need to insert a marker
-
if( tracker.length == 2 ){
-
output[output.length] = '<span>';
-
}
-
}
-
else {
-
// if it is different check if we need to close the marker
-
if(tracker.length > 2){
-
output[output.length] = '</span>';
-
}
-
-
// now reset the tracking array
-
tracker = [];
-
}
-
-
// add to the tracking and output arrays
-
tracker[tracker.length] = item;
-
output[output.length] = item;
-
-
// close up, just incase we are open
-
if( index == ar.length - 1 && tracker.length > 2){
-
output[output.length] = '<span>';
-
}
-
-
});
-
-
document.write(output.join(''));
and here is my live demo.












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