12.11 Kata – triple trouble

This was my second kata of the week and it felt a lot better than the last. I learned more about regex writing and specifically how Regexp wraps text with the “/” characters. That one messed me up because it had an entirely different meaning than I intended. I also used slice instead of split(“”) and pop in order to grab the last item in a string. That is cleaner and (I think) faster.

Here’s the problem on codewars: Triple Trouble.

Here’s my code: 

// https://www.codewars.com/kata/55d5434f269c0c3f1b000058/train/javascript
function tripledouble(num1, num2) {
    let str1 = String(num1)
    let str2 = String(num2)
    let search1 = (str1.match(/(.)\1{2,}/g))
    if (search1) {
      for (let i = 0; i<search1.length; i++){ //iterate through results
        var replace = "(" + search1[i].slice(0,1) + ")\\1{1,}";
        var re = new RegExp(replace); // this adds the wrapping "/" chars
        let search2=(str2.match(re))
        if (search2) return 1
    return 0;


// describe('Initial Tests',_=>{
//   Test.assertEquals(tripledouble(451999277,41177722899),1);
//   Test.assertEquals(tripledouble(1222345, 12345),0);
//   Test.assertEquals(tripledouble(12345, 12345),0);
//   Test.assertEquals(tripledouble(666789, 12345667),1);
//   Test.assertEquals(tripledouble(10560002, 100),1);
//   Test.assertEquals(tripledouble(1112, 122),0);
// });

This was an interesting problem mostly from a “using regex” aspect. It required me to learn a bit more about capture groups. One thing I didn’t initially take into consideration is that the match() method returns a nice object when there is no greedy tag, and it returns a list of matches when there is a greedy tag. That was surprising and required me to shift my strategy in order to iterate through the list, slicing one char from the start as opposed to simply calling the object property that was the repeated character.

Surprisingly the highest voted answers were only a bit smaller than mine, and they mostly seemed to use similar methods. They did end up combining a lot more logic and regexes in one line, and they used regex formats that I haven’t seen before as well. .test() is one that I remember seeing. 

Tell me what you think.

This site uses Akismet to reduce spam. Learn how your comment data is processed.