Intermediate Algorithm Scripting: Pig Latin (Feedback on solution)

Hello,

Here is my solution to the Pig Latin problem from the Javascript Algorithms And Data Structures Certification -> Intermediate Algorithm Scripting track.

function translatePigLatin(str) {
  const isVowel = (str) => /[aeiou]/.test(str)

  if (isVowel(str.charAt(0))) return `${str}way`

  const firstVowel = str.split('').find(char => isVowel(char))

  return firstVowel ? str.replace(/^([^aeiou]+)(\w+)/, '$2$1ay') : `${str}ay`
}

I’d like to hear your opinion on this solution. Any advice will be much appreciated.

Thank you very much.
Alex

1 Like

It could be golfed down to smaller and more efficient, but as it is it’s quite clear and good enough for a challenge solution IMHO. My personal preference would be to change the first test to:

if (/^[aeiou]/.test(str)) return str + 'way';

But your code is still pretty reasonable as-is.

1 Like

Thank you very much for you reply, Chuck. I really appreciate your feedback.

Cheers,
Alex

I came up with another solution:

function translatePigLatin(str) {
  if (str.match(/^[aeiou]/)) { return str + 'way' }

  return str.replace(/(^[^aeiou]+)(\w*)/, "$2$1") + 'ay'
}
1 Like