1

So I wrote a algorithm that takes a word and converts it into Pig Latin. Here it is.

function translatePigLatin(str) {
var vowels = ['a','e','i','o','u']
var splitStr = str.split('');
var newStr = '';
var condition = vowels[0] || vowels[1] || vowels[2] || vowels[3] || vowels[4];
if(splitStr[0] !== condition && splitStr[1] == condition){
  splitStr.push(splitStr[0] + 'ay');
  splitStr.shift();
  newStr = splitStr.join('');
  console.log('first');

} else if (splitStr[0] !== condition && splitStr[1] !== condition) {
  splitStr.push(splitStr[0] + splitStr[1] + 'ay');
  splitStr.shift();
  splitStr.shift();
  newStr = splitStr.join('');
  console.log('second');

} else {
  splitStr.push('way');
  newStr = splitStr.join('');
  console.log('third');
}
console.log(newStr);
}

translatePigLatin("eight");
translatePigLatin("california");
translatePigLatin("paragraphs");
translatePigLatin("glove");
translatePigLatin("algorithm");

All of the result are correct except for 'eight'. For some reason it causing the 'else if' statement to trigger when it should be triggering the 'else' statement. I think this because the 'else if' statement triggers when the first and second letters of the word are not vowels, and the first two letters of the word 'eight' are vowels. I am not looking for a solution as I would like to figure that out myself. I was hoping someone could explain to me why 'eight' is triggering the 'else if' statement and not the 'else' statement. To clarify, 'eight' should be returned as 'eightway' (i.e the 'else' statement). I hope that this makes sense. If not please feel free to ask for clarification. Thank you for your help!

Matt Comeaux
  • 91
  • 2
  • 8

1 Answers1

1

As John Hascall and dandavis commented, condition might not be working in the way you expect.

This statement, splitStr[0] !== condition, is a very imaginative syntax (that kind of makes sense and makes me want to figure out a way to support/hack it :).

In JS, you'll find something like, vowels.includes(splitStr[0]) and !vowels.includes(splitStr[0]) might better perform the comparisons you're striving to make.

The statement, condition = vowels[0] || vowels[1] || vowels[2] || vowels[3] || vowels[4], simply assigns the variable, condition, the first "truthy" variable in the "or" sequence, or the last variable it encounters if all are "falsey."

גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61