DEV Community

Discussion on: Solving "Pig Latin" / freeCodeCamp Algorithm Challenges

Collapse
ttatsf profile image
tatsuo fukuchi • Edited on

You can make it simpler to use the "early-return" technique.

function translatePigLatin(str) {
  const regex = /^[^aeiou]+/g;
  const consonants = str.match(regex);
  if (consonants == null) {
    return str.concat('way');
  }
  else {
    return str
      .replace(regex, '')
      .concat(consonants)
      .concat('ay');
  } 

And, another way using ordinally array-like methods (or, not using the regex):

const innerTPL = head => tail => 
  tail === "" ? 
    head === "" ? ""
    : head + "ay"
  : "aeiou".includes(tail[0]) ? 
    head === "" ? tail + "way"
    : tail + head + "ay"
  : innerTPL(head + tail[0])(tail.slice(1))  

const translatePigLatin = innerTPL("")