i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

RegEx Brain Teaser Part II

In July I published a post calling out puzzle enthusiasts to solve a programming brain teaser that involved grouping duplicates. Some solved it with a hefty amount of code, others used a savvy regular expression. Now I'd like to invite you to yet another brain teaser, except this time your answer must require a regular expression. If you solve it, I would urge you to buy yourself a t-shirt ;)

The Problem

Write a function that takes a text input (first argument), and an integer specifying the amount of duplicates (second argument) to begin the grouping. View the following code as our skeleton:

empty function

function bookend(text, start) {

  // return modified text

}

var example = 'a a a a a a a a a bb bb c c c c d a dd dd dd dd dd dd';



var result = bookend(example, 3);

// result is 'a a a (a a a a a a) bb bb c c c (c) d a dd dd dd (dd dd dd)'



var result2 = bookend(example, 4);

// result2 is 'a a a a (a a a a a) bb bb c c c c d a dd dd dd dd (dd dd)'

In English

Bookend all duplicates that begin after the specific amount of minimum duplicates. Therefore if you specify the offset of '4' as your argument, and there are six duplicates in a row, then bookend the final two. Also take special note of the spaces in the examples.

Assumptions

You can assume your text input will only be a mix of letters (eg: "\w+"), and that nothing is separated by more than a single space.

Sharing

If you come up with a solution, post them offsite. I'd recommend Pastie.org. Happy RegExing! Cheers!

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.