Intermediate Algorithm Scripting: Pig Latin -- intermediate solution explanation

I have a question about the intermediate solution for this challenge (which doesn’t pass the challenge since it only works for words with vowels, as discussed in this issue and therefore has been removed from the challenge, not reflected in the current version), which is:

function translatePigLatin(str) {
  function check(obj) {
      return ['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1 ? check(obj + 1) : obj;
  }

  return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay');
}

Let’s assume this was only used on words containing values – the code explanation states check() will “return the index of whatever it finds to be the last initial consonant i.e., Schmidtsville’s would be 3”. But it looks to me like it would return the first vowel in the string rather than the last initial consonant – is the code explanation just wrong, or am I missing something? The way I read it, it’s checking the array of vowels to see if the character in the provided index of the string is not found, and if not, it continues searching the string until it finds a vowel and when it does, it returns the index containing the vowel.

1 Like

You are correct, The function works correctly, but is explained badly. A translated, logged version of the function:

function translatePigLatin(str) {
  function check(obj) {
    if (['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1) {
      console.log(obj + ' (' + str.charAt(obj) + '): check again');
      return check(obj+1);
    }
    else {
      console.log(obj + ' (' + str.charAt(obj) + '): return ' + obj);
      return obj;
    }

  }

  return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay');
}

console.log(translatePigLatin("Schmidtsville"));
1 Like

The console logs make it crystal clear. Thanks!