freeCodeCamp Challenge Guide: Pig Latin

My solution:

function translatePigLatin(str) {
var index = str.search(/[ueoai]/);
if (index === 0){
return str + “way”;
} else {
return str.slice(index) + str.substr(0,index-0) + “ay”;
}
}

translatePigLatin(“consonant”);

3 Likes

My solution:

function translatePigLatin(str) {
var str = str.toLowerCase(),
vowels = /[^aeiou]+/g;

if (!str[0].match(vowels)) {
return str + ‘way’
}

const extract = (str) => str.match(vowels).slice(0,1).join(’ ‘),
transform = str.replace(extract(str),’’) + extract(str) + ‘ay’;
return transform;
}

translatePigLatin(“trash”);

A similar one liner :slight_smile::

function translatePigLatin(str) {
  return str.match(/^([^aeiou]+)/) ? str.replace(/^([^aeiou]+)(\w+)/, "$2$1ay") : str + "way";
}

translatePigLatin("california");
10 Likes

Here is my solution. I am not sure if anyone else has done the same way. Just want feedback on the efficiency in terms of BigO notations.

function translatePigLatin(str) {
  var vowel = /[(a/e/i/o/u)]/igm;
  var consonant = /[^(a/e/i/o/u)]/igm;
  var v =  str.search(vowel);
  var c =  str.search(consonant);
    return v > c ?  str.slice(v) + str.substr(c, v) + "ay" : str + "way";
}

Here is my solution using a for loop with the method .slice. Seems quite different than the presented solutions. I still don’t really understand regular expressions so this works for now.

function translatePigLatin(str) {
var vowels = [“a”,“e”,“i”,“o”,“u”];
for (var i = 0; i < str.length; i++){
for (var j = 0; j < vowels.length; j++){
if (str[0] === vowels[j]){
return str + “way”;
}
else if(str[i] === vowels[j]){
var consonants = str.slice(0,i);
var slicedStr = str.slice(i);
return slicedStr + consonants + “ay”;
}
}
}
}

translatePigLatin(“paragraphs”);

1 Like

Here is my solution … getting there…

function translatePigLatin(str) {
  var ns;

  var rslt = str.replace((/^[^aeiou]+/gi), function(match, p1, string){
    
    ns = string.substr(match.length);
    ns = ns+ match +"ay";
  });
  
  if (ns === undefined){
    ns = str+ "way";
  }
 
  return ns;
}

translatePigLatin("consonant");

I also solved it with a regex. The logic is basically like this:
If the firstChar matches the regex just take the str (argument) and add “way”.
Otherwise (else) take the substring of str from the position the first vowel is found (str.search(regex) and add from the beginning of str until the first vowel is found. Thats basically shifting the first consonants until the first vowel to the end of str. Of course last but not least add “ay”.

function translatePigLatin(str) {
    var regex = /[aeiou]/i;
    return str.charAt(0).match(regex) ? str + "way" : str.substring(str.search(regex)) + str.substring(0, str.search(regex)) + "ay";
}

translatePigLatin("consonant");
6 Likes

Adding mine here. First a regex to test for vowels, then a loop through the string to find the first vowel. After, depending on first vowel index, concatenate with way or substrings and ay.

function translatePigLatin(str) {
  // Function to check if the characters are vowels
  var firstVowel = -1;
  function vowelTest(s) {
    return (/^[aeiou]$/i).test(s);
  }  
  // First deal with strings starting with vowels
  for (var i = 0; i < str.length; i++) {
      if (vowelTest(str.charAt(i))) {
        firstVowel = i;
        break;
      }
    }
  if (firstVowel === 0) {
    console.log(str.concat('way'));
    return str.concat('way');
  } else {
    console.log(str.substring(firstVowel) + str.substring(0, firstVowel) + "ay");
  }
}

it took me a while and im not sure if i have overcomplicated it but this way made sense to me so I wonder if you guys think there is a problem with it.

function translatePigLatin(str) {
 var re = /[aeiou]/;
  var tempArr = str.split('');
  var charPos;
  var vowelEnd = "way";
  var conEnd = "ay";
  var latinized;
  for (var i = 0; i <tempArr.length ; i ++)
    {
      if (re.test(tempArr[i]) === true){
        charPos = tempArr.indexOf(tempArr[i]);
        break; 
      }
     }
  
  var brokenString = str.substr(charPos);
  var stringBegin = str.substring(0,charPos);
  
  if(charPos === 0){
   latinized = str.concat(vowelEnd);
    
  }
  else {
    latinized = brokenString.concat(stringBegin + conEnd);
    
  }

 
    
  return latinized;
 
}

translatePigLatin("glove");

My solution using regex

    function translatePigLatin(str) {
      // matches one or more occurrences of consonants
      var consonatns = str.match(/[^aeiou]+/i)[0];
      // check if the first letter is a vowel
      var isVowel  = /[aeiou]/i.test(str[0]);
      if (isVowel) {
        str = str + "way";
      } else {
        str = 
          // remove the consonants from the begins of the str
          str.slice(consonatns.length) + 
          // add the removed consonants + "ay"
          consonatns + "ay";
      }
      return str;
    }
2 Likes

Here´s my solution

function translatePigLatin(str) {
	// Array of vowels and indexes
	var vowels = ['a', 'e', 'i', 'o', 'u'];
	var indexOfVowels = [];
	
	var strArr = str.split('');
	var result = [];
	
	// Create an array of the indexes of the vowels
	strArr.forEach(function(letter, index) {
		vowels.forEach(function(vowel){
			if(letter === vowel) {
				indexOfVowels.push(index);
			} 
		});
	});
	
	// Check if first letter is a Vowel
	if(indexOfVowels[0] === 0) {
		result = strArr;
		result.push('way');
	} else {
		result.push(str.substr(indexOfVowels[0]));
		result.push(str.substr(0 ,indexOfVowels[0]));
		result.push('ay');
	}
	return result.join('');
}

translatePigLatin("eight"); 		// should return "eightway".

Wow, looking at these solutions, mine is probably a bit rough. :open_mouth: I filled an array with the first consonant cluster and then used a for loop to iterate through the string and remove each element that had been placed into the array. Then I returned the new string + array + “ay”.

function translatePigLatin(str) {
  var consonant = [];
  
  if (str[0] == "a" || str[0] == "e" || str[0] == "i" || str[0] == "u") {
    return str + "way";
  }
  else {
    for (var i = 0; i < str.length; i++) {
      if (str[i] !== "a" && str[i] !== "e" && str[i] !== "i" && str[i] !== "o" && str[i] !== "u") {
        consonant.push(str[i]);
      }
      else {
        break;
      }  
    }
    
    for (var j = 0; j < consonant.length; j++) {
      str = str.replace(consonant[j], "");
    }
    
    consonant = consonant.join("");
    consonant = consonant.toString();
    return str + consonant + "ay";
  }

}

translatePigLatin("my");

</code>

my solution

function translatePigLatin(str) {
  var firstVowelIndex = str.search(/[aeiou]/);
  return str.slice(firstVowelIndex) + (firstVowelIndex == 0 ? "way" : str.slice(0, firstVowelIndex) + "ay");
}

translatePigLatin("consonant");
5 Likes

I usually begin to hate my solution as soon as I see what other people came up with. Anyway, here is my code. Unfortunately, I did not use regular expressions.

    function translatePigLatin(str) {
     var vowels = ["e", "y", "u", "i", "o", "a"]; 
     var array = str.split("");
      //if it begins with a vowel add "w" to the beginning
    if (vowels.indexOf(array[0]) !== -1) {
      array.unshift("w");
    }
     //move all the consonants to the end of array, one by one
   while (vowels.indexOf(array[0]) === -1)
          {
        array.push(array[0]);
        array.shift();
          } 

      str = array.join("");
      str = str.concat("ay");
        
      return str;
    }

Can anyone show me how to optimize this code?

function translatePigLatin(str){

/* regex for vowels */
var vowels = /[aeiou]/gi;

/* for strings that start with vowels */

//check if the first character is a vowel & add the string 'way' to it
if(str.charAt(0).match(vowels)){
	return str + 'way';
} 

/* for strings that start with consonants */

//extract the first consonants from the string, and create a piglatin  
var con = str.substr(0, str.search(vowels));
var otherStr = str.substr(str.search(vowels));
return otherStr + con +'ay';	

}
translatePigLatin(“consonant”);

I believe my solution is between intermediate and advanced, just taking advantage of the .index property of the result of String.Match Javascript function

function translatePigLatin(str) {
var vowelIndex = str.match('[aeiou]').index;
return (vowelIndex === 0 )?   str.concat('way'):str.substring(vowelIndex).concat(str.substring(0,vowelIndex)).concat('ay');
}
1 Like

function translatePigLatin(str) {
var test = [“a”, “e”, “i”, “o”, “u”];
var arr = str.split("");
var answer;
var x = [];
var i = 0;
var min;
var a;
var b;

for (i; i<test.length; i++) {
if (str.indexOf(test[i])>=0) {
x.push(str.indexOf(test[i]));
}
min = Math.min.apply(null, x);
if (a == 0) {
answer = str + “way”;
} else {
a = str.substr(0, min);
b = str.substr(min);
answer = b + a + “ay”;
}
}
return answer;

}

translatePigLatin(“eight”);

I really like the regex solutions on this page. Much more concise and readable. I know what I need to study now!

I took the approach of comparing each character of the string against an array of vowels. If the first character is a vowel, I simply return the string plus “way”. Otherwise, I look for the next index of the string where it finds a vowel, use that index as the slice point, and add “ay”.

function translatePigLatin(str) {
  var vowels = ["a", "e", "i", "o", "u"];
  if (vowels.indexOf(str.charAt(0)) > -1) return str + "way";
  for (var i = 1; i < str.length; i++) {
    if (vowels.indexOf(str.charAt(i)) > -1) {
      str = str.slice(i) + str.slice(0, i) + "ay";
      return str;
    }
  }
}

Hello everyone!

Such diverse solutions, different strokes “from” different folks.

Oh well, here’s my stroke :wink: :

function translatePigLatin(str) {
  
  var consonants = "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z".split(","),
      pigLatin = "";
  
  for(var i = 0; i < consonants.length; i++) {
    for(var j = 0; j < consonants.length; j++){
         
      if(str[0] === consonants[i]) {
        pigLatin = str.substr(1, j) + str[0] + "ay";
      } else if(str[1] === consonants[i]) {
        pigLatin = str.substr(2, j) + str[0] + str[1] + "ay";
      } else if(/[aeiou]/.test(str[0]) === true) {
        pigLatin = str + "way";
      }       
    }
  }
  return pigLatin;
}

translatePigLatin("algorithm");

function translatePigLatin(str) {

str = str.split(’’);
var vowels = [‘a’,‘e’,‘i’,‘o’,‘u’];
var newstr;

// Verify if first char is equal a vowel
var firstVowel = vowels.filter(function(a){
return a===str[0];
});

// Verify if second char is equal a vowel
var secondVowel = vowels.filter(function(b){
return b===str[1];
});

if(firstVowel.length>0){
newstr = str.join(’’) + “way”;
} else if(secondVowel.length>0) {
newstr = str.join(’’).substr(1) + str[0] + “ay”;
} else {
newstr = str.join(’’).substr(2) + str[0] + str[1] + “ay”;
}

return newstr;

}

translatePigLatin(“glove”);