I need help executing an if-function - My "if-function" executes, as well as my "else-function"? - javascript

Hi have this code below to check whether the first letter is a vowel or a consonant. If it is a vowel, you take the word and add "way" to the end. If it is a consonant, it moves the first letter to the end and suffixes an "ay" For some reason, when it is a vowel, it executes my else function? Any help would be appreciated. Here is my code:
function translatePigLatin(str) {
var vowels = ["a", "e", "i", "o", "u"];
for (i = 0; i < vowels.length; i++) {
if (str.charAt(0) === vowels[i]) {
return str += "way";
} else {
var first = str.charAt(0);
return str.substr(1, str.length) + first;
}
}
}
console.log( translatePigLatin("eight") );

The reason you get "ighte" instead of "eightway" is the first time your loop runs, you're comparing the first letter of the string ("e") with the first vowel in your vowels array ("a").
You can do without the for loop by using includes().
function translatePigLatin(str) {
if (["a", "e", "i", "o", "u"].includes(str.charAt(0))) {
return str += "way";
}
else {
var first = str.charAt(0);
return str.substr(1, str.length) + first;
}
}
If your intention with the for loop was to keep iterating the function until it encounters a vowel, then we can use this:
function translatePigLatin(str) {
for (var i = 0; i < str.length; i++) {
if (["a", "e", "i", "o", "u"].includes(str.charAt(i))) {
return str += "way";
}
else {
var first = str.charAt(0);
str = str.substr(1, str.length) + first;
}
}
}

This is happening because, if condition checks for 'a' as the first vowel of the word and if the character does not match it goes to else statement. Hence here rest of the vowels are not being checked, Ideal way would be to first check for all vowels and then do else part below is the code
function translatePigLatin(str) {
var vowels = ["a", "e", "i", "o", "u"];
var first = str.charAt(0);
for (i = 0; i < vowels.length; i++) {
if (first === vowels[i]) {
return str += "way";
}
}
return str.substr(1, str.length) + first;
}
console.log( translatePigLatin("eight") );

Your for loop will only ever run once as even if your first condition fails your else will be taken and therefore it will return. Consider moving the else logic from the loop.
function translatePigLatin(str) {
var vowels = ["a", "e", "i", "o", "u"];
for (i = 0; i < vowels.length; i++) {
if (str.charAt(0) === vowels[i]) {
return str += "way";
}
}
var first = str.charAt(0);
return str.substr(1, str.length) + first + "ay";
}
console.log( translatePigLatin("eight") );

Try something like this:
function translatePigLatin(str) {
var vowels = ["a", "e", "i", "o", "u"];
var firstVowel = false;
for (var i = 0; i < vowels.length; i++) {
if (str.charAt(0) === vowels[i]) {
firstVowel = true;
}
}
if (firstVowel) {
return str += "way";
} else {
var first = str.charAt(0);
return str.substr(1, str.length) + first + "ay";
}
}
console.log( translatePigLatin("eight") );
console.log( translatePigLatin("run") );

Related

if (condition) else return statements where there is no output even when the if block is true

Hello I've just started learning JS and currently doing tutorial project on loops, basically taking the phrase "coconut closet" and translating it into "whale talk" equivalent = oouoe
I've already learnt that the else block is optional where you can have an if without an else; but on my first try when not knowing this, I included an else statement to the if statement. This in turn, when run on the console it had no ouput. Here is the code in question below:
let input = "coconut closet";
const vowels = ["a", "e", "i", "o", "u"];
let resultArray = [];
for (let i = 0; i < input.length; i++) {
for (let j = 0; j < vowels.length; j++) {
if (input[i] === vowels[j]) {
resultArray.push(vowels[j]);
} else return;
}
}
let resultString = resultArray.join('')
console.log(resultString);
I've tried to look for an explanation but currently unable to find any, can someone please explain why my code has no output?
I've tried this both on codecademy's IDE and VS Node.
You should check the console when executing your code, your else statement returns false outside of a function and inside it, it will stop the end of the function. And it is useless.
let input = "coconut closet";
const vowels = ["a", "e", "i", "o", "u"];
let resultArray = [];
for (let i = 0; i < input.length; i++) {
if (input[i] === "e") {
resultArray.push("e");
} else if (input[i] === "u") {
resultArray.push("u");
}
for (let j = 0; j < vowels.length; j++) {
//console.log(`j is ${j}`);
if (input[i] === vowels[j]) {
//console.log(input[i]);
resultArray.push(vowels[j]);
}
}
}
//console.log(resultArray);
let resultString = resultArray.join('').toUpperCase();
alert(resultString);

How to filter vowel and consonant letters generated from a random string

I am making a word game that picks 8 random letters from the alphabet and the player must find words that use these letters. I must find out a way to make the letters picked always contain 3 vowels and 5 consonants. I would appreciate your help
Here is the code I am using to pick the random letters for the game
function makeid(length) {
var result = '';
var characters = 'aaabcdeeefghiiijklmnooopqrstuuuvwxyz';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
let letter = characters.charAt(Math.floor(Math.random() * charactersLength));
while (result.match(letter)) {
letter = characters.charAt(Math.floor(Math.random() * charactersLength));
}
result += letter;
}
return result;
}
console.log("Id of 8 characters", makeid(8))
#Lars answer is almost perfect, the only problem is that the final string is not truly shuffled.
I suggest you just create two arrays: random vowels and random consonants and then just shuffle them using Fisher-Yates' algorithm.
function getRandomCharsFromString(str, length) {
return Array.from({length}, () => {
return str[Math.floor(Math.random() * str.length)]
});
}
function shuffle(str) {
var a = str.split(""),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
// Swap them with ES6 destructuring magic
[a[i], a[j]] = [a[j], a[i]];
}
return a.join("");
}
function getRandomString() {
const vowels = 'aeiou';
const consonants = 'bcdfghjklmnpqrstvwxyz';
const randomVowels = getRandomCharsFromString(vowels, 3);
const randomConsonants = getRandomCharsFromString(consonants, 5);
const randomWord = [...randomVowels, ...randomConsonants].join('')
return shuffle(randomWord)
}
console.log('random string:', getRandomString())
No repeated letters
You mentioned you don't want repeated letters; many words in English have duplicate letters. Why is that a requirement?
You can shuffle the vowels and consonants and get the first x characters from that string.
// This version makes sure characters are not repeated
function getRandomCharsFromString(str, length) {
return shuffle(str).slice(0, length);
}
function shuffle(str) {
var a = str.split(''),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
// Swap them with ES6 destructuring magic
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function getRandomString() {
const vowels = 'aeiou';
const consonants = 'bcdfghjklmnpqrstvwxyz';
const randomVowels = getRandomCharsFromString(vowels, 3);
const randomConsonants = getRandomCharsFromString(consonants, 5);
const randomWord = [...randomVowels, ...randomConsonants].join('')
return shuffle(randomWord).join('')
}
console.log('random string:', getRandomString())
It's a lot of code, but this works for me.
The function begins with a for-loop, which generates 8 different letters.
inside of that loop, Math.random() makes it a 37.5% chance that a vowel will be added to the randomArray, and 62.5% that a consonant will be added (8 characters from which 3 are vowels, so 3 / 8 = 0.375).
when that is done 8 times (cuz of the for loop), the array will be turned into a string, and the function will return the string (which is by then an 8-digit letter code with 3 vowels and 5 consonants).
I hope this explanation helps(;
function getRandomString() {
const vowels = 'aeiou'
const consonants = 'bcdfghjklmnpqrstvwxyz'
let randomArray = []
let amountOfVowels = 0
let amountOfConsonants = 0
for (let i = 0; i < 8; i++) {
if (Math.random() < 0.375 && amountOfVowels < 3) addVowel()
else if (amountOfConsonants < 5) addConsonant()
else addVowel()
}
function addVowel() {
randomArray.push(vowels[Math.floor(Math.random() *
vowels.length)])
amountOfVowels++
}
function addConsonant() {
randomArray.push(consonants[Math.floor(Math.random() *
consonants.length)])
amountOfConsonants++
}
let finalString = ''
for (let i = 0; i < 8; i++) {
finalString += randomArray[i]
}
return finalString;
}
console.log('random string:', getRandomString())
Have one array of consonants and one array for vowels.
Use a shuffling function, here's a terse one liner:
const shuffle = array => array.sort(() => Math.random() - 0.5);
The function above will return a given array in a random order, so you'll need to shorten each array by 5 (consonants) and 3 (vowels):
let C = shuffle(consonants);
let V = shuffle(vowels);
C.length = 5;
V.length = 3;
Easy 😎
// Utility Function (optional)
const log = data => console.log(JSON.stringify(data));
const consonants = ["B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z"];
const vowels = ["A", "E", "I", "O", "U"];
const shuffle = array => array.sort(() => Math.random() - 0.5);
let C = shuffle(consonants);
let V = shuffle(vowels);
C.length = 5;
V.length = 3;
const result = shuffle(V.concat(C));
log(result);

Pig Latin Converter Issue

Im working on a function that converts a normal word to pig latin, and I can't get everything to come together; it has to work for california, gloves, and eight. What isn't working right?
function translate(word) {
var result = "";
for (var i = 0; i < word.length; i++) {
if (["a", "e", "i", "o", "u"].indexOf(word[-1]) === -1) {
// probably failing around here
result = word.slice(i);
result += word.slice(0, i);
break;
}
}
if (["a", "e", "i", "o", "u"].indexOf(word[0]) !== -1) {
result = word + "way";
} else {
result += "ay";
}
return result;
}
Here is your working function, When asking this type of questions for a solution describe clearly what you tried so far in you question and what you looking for.
function translateW(word) {
var result = "", e="";
if (["a", "e", "i", "o", "u"].indexOf(word[0]) !== -1) {
return word + "way";
}
for (var i = 0; i < word.length; i++) {
if (["a", "e", "i", "o", "u"].indexOf(word[i])!== -1) {
e = word.slice(0, i);
result = word.slice(i);
result += e;
break;
}
}
return result += "ay";
}

Returning a string with only vowels capitalized

I'd like to return the variable newString with only vowels capitalized. Not sure how to proceed. Tried using an if/else block but my logic wasn't correct.
function LetterChanges(str) {
var newArray = [];
for (var i = 0; i < str.length; i++) {
var strCode = str.charCodeAt(i) + 1;
var strLetter = String.fromCharCode(strCode);
newArray.push(strLetter);
var newString = newArray.join("");
}
return newString;
}
LetterChanges("hello");
This is different from your approach, but you can do this:
function LetterChanges(str) {
return str.toLowerCase().replace(/[aeiou]/g, function(l) {
return l.toUpperCase();
});
}
console.log(LetterChanges("The Quick Brown Fox Jumped Over The Lazy Dog"));
Here's an approach that's closer to your attempt and uses somewhat simpler concepts:
function LetterChanges(str) {
var newArray = [];
for (var i = 0; i < str.length; i++) {
var ch = str.charAt(i);
if ('aeiouAEIOU'.indexOf(ch) !== -1) {
newArray.push(ch.toUpperCase());
} else {
newArray.push(ch.toLowerCase());
}
}
return newArray.join("");
}
Split, map, join.
var vowels = 'aeiou';
var text = 'my random text with inevitable vowels';
var res = text.split('').map(function(c){
return (vowels.indexOf(c) > -1) ? c.toUpperCase() : c;
});
See the fiddle: http://jsfiddle.net/zo6j89wv/1/
Strings are Collections of word-characters, so you can directly access each part of the string:
var foo = 'bar';
console.log(foo[0]); // outputs 'b'
Hence you can extend this to uppercase the output:
console.log(foo[0].toUpperCase() // outputs 'B'
To do this without regex, you can set the string to lower case, then iterate once over, calling toUpperCase() on each vowel.
function letterChanges(string){
var vowels = 'aeiou';
var lowerString = string.toLowerCase();
var result = '';
for( var i=0; i<lowerString.length; i++){
if( vowels.indexOf( lowerString[i] ) >= 0 ){ //if lowerString[i] is a vowel
result += lowerString[i].toUpperCase();
} else {
result += lowerString[i]
}
}
return result;
}
const vowelSound = string => {
let res = string.split("").filter(item => item === 'a' || item === 'i' || item === 'e' || item === 'o' || item === 'u')
return res.join("")
}

String - Vowels to uppercase, letters to next in alphabet - Javascript

I'm trying to convert all the letters of the string to the following letter of the alphabet, e.g. A should become B, X should become Y, Z should become A etc.
I want to capitalize every vowel after the letter shifting is done.
function LetterChanges(str) {
var c = str.split("");
var vowels = ["a", "e", "i", "o", "u"];
if (c == vowels) {
vowels.toUpperCase();}
if (c == "z") return "a";
return str.replace(/[a-z]/gi, function(s) {
return String.fromCharCode(s.charCodeAt(c)+1);
});
}
LetterChanges("cold buttz");
The vowels part and the z to a part is not working. Please help?
See if this helps:
var str = 'cold buttz';
str = str.replace(/[a-z]/gi, function(char) {
char = String.fromCharCode(char.charCodeAt(0)+1);
if (char=='{' || char=='[') char = 'a';
if (/[aeiuo]/.test(char)) char = char.toUpperCase();
return char;
});
console.log(str); //= "dpmE cvUUA"
Edit: I can see your code was sort of a messy copy/paste from my last answer... Here's a brief description of what's wrong with it:
function LetterChanges(str) {
var c = str.split(""); // array of letters from `str`
var vowels = ["a", "e", "i", "o", "u"]; // array of vowels
// `c` and `vowels` are two different objects
// so this test will always be false
if (c == vowels) {
// `toUpperCase` is a method on strings, not arrays
vowels.toUpperCase();
}
// You're comparing apples to oranges,
// or an array to a string, this test will also be false
// Then you return 'a'?? This was meant to be inside the `replace`
if (c == "z") return "a";
// OK, I see you recycled this from my other answer
// but you copy/pasted wrong... Here you're basically saying:
// "For each letter in the string do something and return something new"
return str.replace(/[a-z]/gi, function(s) { // `s` is the letter
// Here we find out the next letter but
// `c` is an array and `charCodeAt` expects an index (number)
return String.fromCharCode(s.charCodeAt(c)+1);
// `.charCodeAt(0)` gives you the code for the first letter in a string
// in this case there's only one.
});
}
My solution does exactly what you asked for. The letters are first shifted in the alphabet and then the vowels are uppercased.
Have a look:
function LetterChanges(str) {
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var ret = new Array();
for (var x=0; x < str.length; x++) {
for(var i=0; i < alphabet.length; i++) {
if (checkIfCharInString(alphabet, str[x]) == false) {
ret[x] = str[x].toString();
break;
}
if (str[x] == alphabet[i]) {
if (alphabet[i] == "Z") {
ret[x] = "A";
} else {
ret[x] = alphabet[i+1];
}
}
}
}
var output = ret.join("");
output = capitalizeVowels(output);
// code goes here
return output;
}
function checkIfCharInString(motherString, char)
{
for(var i=0; i < motherString.length; i++) {
if (motherString[i] == char.toString()) {
return true;
}
}
return false;
}
function capitalizeVowels(str)
{
var vowel = "aeiou";
var newStr = new Array();
for(var i=0; i < str.length; i++) {
for(var x=0; x < vowel.length; x++) {
newStr[i] = str[i];
if (str[i] == vowel[x]) {
newStr[i] = vowel[x].toUpperCase();
break;
}
}
}
return newStr.join("");
}
console.log(LetterChanges("Hello*3"));
console.log(LetterChanges("I love stackoverflow!"));
console.log(LetterChanges("I have Internet explorer!!"));

Categories