Pig Latin solution critique

Hi, I have a few questions regarding my Pig Latin solution. Challenge link

I’m alright with all but the last challenge tests where it says that, my solution has to handle strings without vowels. Well it does, but how well? When you look at my code, you’ll see that I process every string in the same way, regardless its’ composition. So when I encounter a string like “grrr”, for my code to simply add “ay” at the end of it, I process it as it had vowels. But then I think, to make it simpler would mean more lines of code and more conditions to check, so wouldn’t it make the program slower? I hope you understand my point. Here’s the solution:

function translatePigLatin(str) {
  "use strict"
  // Create variables to be used:
  let regex = /^[^aeiou]+/; // The beginning of the string doesn't start with one or more vowels

  // Check if the string passes the regex test
  // If it does, move them to the end of the string and add 'ay'
  // Otherwise add 'way' to the end of the string
  return regex.test(str) ? 
    `${str.slice(str.match(regex).toString().length, ).concat(str.match(regex).toString())}ay` :
    `${str}way`;
}

translatePigLatin("consonant");

EDIT:
And why when I try to bind str.match(regex).toString() to a variable and use it in the return statement, console throws me this: TypeError: Cannot read property 'toString' of null only when I provide words starting with the vowel? The test fails to find consonants, so shouldn’t code proceed to the last statement?

Only numbers can use the toString method. If your match returns null, then it will error out as you have noticed.

1 Like