I have working Javascript code that that converts any number entered into its text equivalent - javascript

For example, 4 is converted to "Four" and 33333 is converted to "Thirty three thousands three hundred and thirty three". I am thinking of using JQUERY instead of plain JAVASCRIPT.
Here is the code in its entirety:
<script language="javascript" type="text/javascript">
function NumberToTextConverter()
{
this.TEN = 10;
this.HUNDRED = 100;
this.THOUSAND = 1000;
this.MILLION = 1000000;
this.BILLION = 1000000000;
this.wordList = new Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "TEN", "ELEVEN", "Twelve", "Thirteen", "Fourteen", "fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
this.wordList2 = [];
this.initializeTwentys(); // this would populate the twentys
}
NumberToTextConverter.Convert = function(number)
{
var currentConverter = new NumberToTextConverter();
return currentConverter.Convert(number);
};
NumberToTextConverter.prototype.Convert = function(number)
{
var quotient = Math.floor(number / this.BILLION);
var remainder = number % this.BILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.BILLION)
{
return converter.ConvertToMillions(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " billions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " billions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " billions ";
}
realValue = realValue + converter.ConvertToMillions(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertToMillions = function(number)
{
var quotient = Math.floor(number / this.MILLION);
var remainder = number % this.MILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.MILLION)
{
return converter.ConverToThousands(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " millions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " millions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " millions ";
}
realValue = realValue + converter.ConverToThousands(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConverToThousands = function(number)
{
var quotient = Math.floor(number / this.THOUSAND);
var remainder = number % this.THOUSAND;
var word = "";
var realValue = "";
var converter = this;
if (number < this.THOUSAND)
{
return converter.ConvertHundreds(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " thousands ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " thousands ";
}
else
{
realValue = realValue + this.wordList[quotient] + " thousands ";
}
realValue = realValue + converter.ConvertHundreds(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertHundreds = function(number)
{
var quotient = Math.floor(number / this.HUNDRED);
var remainder = number % this.HUNDRED;
var word = "";
var converter = this;
if (number >= 100)
{
return this.wordList[quotient] + " hundred " + converter.ConvertToDoubleDigit(remainder);
}
else
{
return converter.ConvertToDoubleDigit(remainder);
}
};
NumberToTextConverter.prototype.initializeTwentys = function()
{
this.wordList2[0] = "";
this.wordList2[1] = "TEN";
this.wordList2[2] = "TWENTY";
this.wordList2[3] = "THIRTY";
this.wordList2[4] = "FOURTY";
this.wordList2[5] = "FIFTY";
this.wordList2[6] = "Sixty";
this.wordList2[7] = "Seventy";
this.wordList2[8] = "Eighty";
this.wordList2[9] = "Ninety";
};
NumberToTextConverter.prototype.ConvertSingleDigit = function(number)
{
return this.wordList[number];
};
NumberToTextConverter.prototype.ConvertToDoubleDigit = function(number)
{
var quotient = Math.floor(number / this.TEN);
var remainder = number % this.TEN;
var word = "";
if (number > 19)
{
switch (quotient)
{
case 2: word = this.wordList2[2]; break;
case 3: word = this.wordList2[3]; break;
case 4: word = this.wordList2[4]; break;
case 5: word = this.wordList2[5]; break;
case 6: word = this.wordList2[6]; break;
case 7: word = this.wordList2[7]; break;
case 8: word = this.wordList2[8]; break;
case 9: word = this.wordList2[9]; break;
}
return word + " " + this.wordList[remainder];
}
else
{
return this.wordList[number];
}
};
function PleaseConvert()
{
var value = document.getElementById("txtNumberInput").value;
var checkValue = NumberToTextConverter.Convert(parseInt(value));
var currentSpanTag = document.getElementById("spanText");
currentSpanTag.style.backgroundColor = '#aadd88';
currentSpanTag.style.border = 'dotted 1px #333377';
currentSpanTag.innerHTML = checkValue;
}
Your opinions and ideas are appreciated!! My Question is whether it would be good idea to spend time by implementing this logic using JQUERY? Here is the working code :
http://www.coolaspdotnetcode.com/Web/JavaScriptInfoAndCode.aspx

What exactly do you mean by "convert to jQuery code"? jQuery has really pretty much nothing to do with the code you posted. It is not a different language, it has no magic that will make the Javascript any different. jQuery is a library intended to make it easy to manipulate DOM elements and perform common Javascript tasks cross-browser. It is Javascript, and there's nowhere really where it would fit to have a function such as this one.
If what you really mean is "make a plugin out of this", then it's a 5 liner:
$.fn.humanizeNumber = function() {
return this.each(function() {
$(this).html(CALLTHEFUNCTION($(this).html()));
}
});
Where CALLTHEFUNCTION is whatever is the main function of the code you posted above (I don't really care to go through it and find what it is). That plugin would then let you do this:
$('#myelement').humanizeNumber();
To convert the value in #myelement from "123" to whatever your function returns.

If it's already done this way and it's working I don't see why spending time implementing this in jQuery.
Unless if you want to learn/practice jQuery.

If your code works, then no, don't refactor. Why? Because we don't have much time here, on Earth.

I think a better place for this would be http://refactormycode.com/
Stackoverflow is more geared towards direct Question and Answers, and less for discussions.

Related

Simple card game

I've created a simple higher or lower card guessing game, it works but once it completes once it then loops through the game logic n^2 times and I cant explain why. I'm really new to coding and JavaScript and I cant figure out what's happening. The issue I currently have is while I'm able to look up concepts in isolation I don't understand enough about the bigger picture to know what interaction is causing the looping.
less useful further info:
Currently the whole script is really a proof of concept, ultimately I will replace the deck building function and just use the random number generator to find images of cards, record all of the previous game events and remove cards from the deck as the game progresses but I cant have it looping by the square of the number of times its been through the game cycle.
Here is the code, please feel free to talk to me like I'm 5, I currently feel like a monkey with a gun.
console.log(">>>>>>>>>>>>>>>>>>>>>>> SCRIPT START");
console.log("variables are defined");
var suitClubs = [];
var suitDiamonds = [];
var suitHearts = [];
var suitSpade = [];
var history = [];
var userGuess;
var activeCard;
var nextCard;
var randomSuitOne;
var randomCardOne;
var randomSuitTwo;
var randomCardTwo;
var activeCardValue;
var nextCardValue;
var gameCycle = 0;
const card = document.querySelector(".card");
const title = document.querySelector(".title");
const historyP = document.querySelector(".history-p");
console.log("buildDeck() is called")
buildDeck();
function buildDeck() {
console.log("Deck is built");
for (i = 1; i <= 13; i++) {
suitDiamonds.push(i + " Diamond");
}
for (i = 1; i <= 13; i++) {
suitHearts.push(i + " Heart");
}
for (i = 1; i <= 13; i++) {
suitClubs.push(i + " Club");
}
for (i = 1; i <= 13; i++) {
suitSpade.push(i + " Spade");
}
var deck = suitClubs.concat(suitDiamonds, suitHearts, suitSpade);
console.log("cardChoice is called");
cardChoice();
};
function cardChoice() {
gameCycle = gameCycle + 1;
console.log(">>>>>>>>>>>>>>>>>>>>>>> GAME CYCLE START");
title.innerHTML = "Higher or Lower!"
activeSequenceCard();
// console.log("activeSequenceCard is called to randomize the active card");
function activeSequenceCard() {
randomSuitOne = Math.floor((Math.random() * 4) + 1);
randomCardOne = Math.floor((Math.random() * 13));
switch (randomSuitOne) {
case 1:
activeCard = suitClubs[randomCardOne];
break;
case 2:
activeCard = suitDiamonds[randomCardOne];
break;
case 3:
activeCard = suitSpade[randomCardOne];
break;
case 4:
activeCard = suitHearts[randomCardOne];
break;
}
card.innerHTML = activeCard;
nextSequenceCard();
// console.group("nextSequenceCard is called to randomize the next card in the deck")
}
function nextSequenceCard() {
randomSuitTwo = Math.floor((Math.random() * 4) + 1);
randomCardTwo = Math.floor((Math.random() * 13));
switch (randomSuitTwo) {
case 1:
nextCard = suitClubs[randomCardTwo];
break;
case 2:
nextCard = suitDiamonds[randomCardTwo];
break;
case 3:
nextCard = suitSpade[randomCardTwo];
break;
case 4:
nextCard = suitHearts[randomCardTwo];
break;
}
historyP.innerHTML = ("The next card will be: " + nextCard);
console.log("randomSuitOne is: " + randomSuitOne + " randomCardOne is: " + randomCardOne);
console.log("randomSuitTwo is: " + randomSuitTwo + " randomCardTwo is: " + randomCardTwo);
gamePlay();
}
}
function gamePlay() {
for (let i = 0; i < 2; i++) {
document.getElementsByClassName("game-button")[i].addEventListener("click", function () {
userGuess = parseInt(this.value);
console.log("The users guess was button (" + this.value + ") " + this.innerHTML + " and is a: " + typeof this.value);
switch (userGuess) {
case 1: console.log("User clicked HIGHER");
if (activeCardValue <= nextCardValue) {
console.log("Case 1: TRUE fired");
title.innerHTML = "CORRECT!"
setTimeout(cardChoice, 2000);
break;
} else {
console.log("Case 1: FALSE fired");
title.innerHTML = "GAME OVER!"
}
break;
case 2: console.log("User clicked LOWER");
if (activeCardValue >= nextCardValue) {
console.log("Case 2: TRUE fired");
title.innerHTML = "CORRECT!"
setTimeout(cardChoice, 2000);
break;
} else {
console.log("Case 2: FALSE fired");
title.innerHTML = "GAME OVER!"
}
break;
} console.log(">>>>>>>>>>>>>>>>>>>>>>> GAME CYCLE ENDS, this is cycle: " + gameCycle);
})
}
activeCardValue = activeCard.split(" ");
activeCardValue = parseInt(activeCardValue.splice(0, 1));
console.log("activeCardValue is: " + activeCardValue);
nextCardValue = nextCard.split(" ");
nextCardValue = parseInt(nextCardValue.splice(0, 1));
console.log("nextCardValue is: " + nextCardValue);
}

Displaying a hint mode in a hangman game js UPDATE

Now after implementing the hint mode, the guessing part does not work, meaning I cannot guess a letter. This means that the lives do not reduce and no one can win or lose the game. The hint mode works perfectly.
function setup() {
alphabet = "abcdefghijklmnopqrstuvwxyz";
lives = 8;
var words = ["ayeupmeducks", "pieceofcake",
"bullinachinashop", "hangfire","greeneyedmonster",
"hairraising","bringhomethebacon","adiamondintherough","onceinabluemoon",
"afootinthedoor","bitethebullet"];
messages = {
win: 'Congratulations you have won the game of Hangman!',
lose: 'You have been Hanged !!',
guessed: ' already guessed, please try again...',
validLetter: 'Please enter a letter from A-Z'
};
var getHint = document.getElementById("hint");
var showClue = document.getElementById("clue");
getHint.onclick = function() {
hints = ["Stoke Greeting","Saying Something is Easy",
"Very Clumsy","delaying something for a minute",
"When you are jealous of something",
"Something is frightening", "Earn Money",
"Rough Exterior however has some potential",
"When something rarely happens",
"When you have succeeded/ getting yourself known by a company",
"accepting something , when you do not want to"];
var hintIndex = words
showClue.innerHTML = "Clue: - " + hints [idx];};
gussedLetter = matchedLetter = '';
numberofMatchedLetters = 0;
var idx = Math.floor(Math.random() * words.length);
var currentWord = words[idx];
output = document.getElementById("output");
message = document.getElementById("message");
guessInput = document.getElementById("letter");
message.innerHTML = 'You have ' + lives + ' lives remaining';
output.innerHTML = '';
document.getElementById("letter").value = '';
guessButton = document.getElementById("guess");
guessInput.style.display = 'inline';
guessButton.style.display = 'inline';
letters = document.getElementById("letters");
letters.innerHTML = '<li class="current-word">Current word:</li>';
var letter, i;
for (i = 0; i < currentWord.length; i++) {
letter = '<li class="letter letter' + currentWord.charAt(i).toUpperCase() + '">' + currentWord.charAt(i).toUpperCase() + '</li>';
letters.insertAdjacentHTML('beforeend', letter);
}
}
function gameOver(win) {
if (win) {
output.innerHTML = messages.win;
output.classList.add('win');
} else {
output.innerHTML = messages.lose;
output.classList.add('error');
}
guessInput.style.display = guessButton.style.display = 'none';
guessInput.value = '';
}
window.onload = setup();
document.getElementById("restart").onclick = setup;
guessInput.onclick = function () {
this.value = '';
};
document.getElementById('hangman').onsubmit = function (e) {
if (e.preventDefault) e.preventDefault();
output.innerHTML = '';
output.classList.remove('error', 'warning');
guess = guessInput.value;
if (guess) {
if (alphabet.indexOf(guess) > -1) {
if ((matchedLetter && matchedLetter.indexOf(guess) > -1) || (gussedLetter && gussedLetter.indexOf(guess) > -1)) {
output.innerHTML = '"' + guess.toUpperCase() + '"' + messages.guessed;
output.classList.add("warning");
}
else if (currentWord.indexOf(guess) > -1) {
var lettersToShow;
lettersToShow = document.querySelectorAll(".letter" + guess.toUpperCase());
for (var i = 0; i < lettersToShow.length; i++) {
lettersToShow[i].classList.add("correct");
}
for (var j = 0; j < currentWord.length; j++) {
if (currentWord.charAt(j) === guess) {
numberofMatchedLetters += 1;
}
}
matchedLetter += guess;
if (numberofMatchedLetters === currentWord.length) {
gameOver(true);
}
}
else {
gussedLetter += guess;
lives--;
message.innerHTML = 'You have ' + lives + ' lives remaining';
if (lives === 0) gameOver();
}
}
else {
output.classList.add('error');
output.innerHTML = messages.validLetter;
}
}
else {
output.classList.add('error');
output.innerHTML = messages.validLetter;
}
return false;
};
The variables as far as I can see are still the same, so I do not get why an error occurs?.
You declared an array containing an array :
hints = [
["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"]
];
Change it to a simple array :
hints = ["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"];
In addition to the array in array problem, you also need to store the index itself and use that instead of the word.
Also you have typo: hint.onclick should be getHint.onclick.
var words = ["ayeupmeducks", "pieceofcake", "bullinachinashop", "hangfire","greeneyedmonster", "hairraising","bringhomethebacon","adiamondintherough","onceinabluemoon","afootinthedoor","bitethebullet"];
var idx = Math.floor(Math.random() * words.length);
var currentWord = words[idx];
var getHint = document.getElementById("hint");
var showClue = document.getElementById("clue");
getHint.onclick = function() {
var hints = ["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"];
showClue.innerHTML = "Clue: - " + hints [idx];
};
<button id="hint" name="hint" type="button">Hint</button>
<p id="clue">Clue: </p>
Sorted it- Thank you for all your help :)
I changed it current word from being a variable and now it works

Object function not working in JS

This is a function for a simple shopping app (kinda) thing that I coded to work on my JS skills, considering my elementary experience in it. But everything works except for one thing:
The applyStaffDiscount function doesn't seem to work. Everytime I try to apply an employee discount, the program just returns the same original value that was present before trying to apply the discount. Please help and also let me know how I can improve this program.
function StaffMember(name, discountPercent) {
this.name = name;
this.discountPercent = discountPercent;
}
var sally = new StaffMember("sally", 5);
var bob = new StaffMember("bob", 10);
var arhum = new StaffMember("arhum", 20);
var cashRegister = {
total: 0,
lastTransactionAmount: 0,
add: function(itemCost) {
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item, quantity) {
switch (item) {
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction: function() {
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
applyStaffDiscount: function(employee) {
this.total -= (this.total * (employee.discountPercent/100))
}
};
var cont = confirm("Are you ready to shop?")
while (cont) {
var user = ("Choose your function: A to Add Item, ED for Employee Discount, VT to Void Transaction or just X to Close")
var askUser = prompt(user).toUpperCase()
if (askUser === "A") {
var itemName = prompt("What item would you like?", "Eggs, Milk, Magazine, Chocolate").toLowerCase()
var itemNum = prompt("How many?")
cashRegister.scan(itemName, itemNum)
var cont = confirm("Your total bill is $" + cashRegister.total.toFixed(2) + ". Would you like anything else?")
}
else if (askUser === "ED") {
var name1 = prompt("Please enter you name").toLowerCase()
cashRegister.applyStaffDiscount[name1]
alert("Your total bill is $" + cashRegister.total.toFixed(2) + ".")
}
else if (askUser === "VT") {
cashRegister.voidLastTransaction()
alert("Your previous transaction has been voided. Your total bill is $" + cashRegister.total.toFixed(2) + " now.")
}
else if (askUser === "X") {
cont = false
}
if (cont === false) {
alert("We hope you had a good time. have a nice day!")
}
}
calling applyStaffDiscount should be done as shown below
cashRegister.applyStaffDiscount(name1);
Then inside applyStaffDiscount function, it should be accessed as below
this.total -= (this.total * (window[employee].discountPercent/100))
You didn't call the function in here:
cashRegister.applyStaffDiscount[name1]
Try it with something like this:
cashRegister.applyStaffDiscount(name1);

simple calculator returning alert statments but ignoring actual functions

hey everyone im in my first semester and im pretty new to javascript. i have an assignment thats due in in a few hours and i have been racking my brain trying to figure out why my code wont display the actual function results. this is the assignment.
**Write JavaScript program which implements a fully functioning, five feature
(addition, subtraction, multiplication, division, and modulo/remainder) calculator.
when i run my code it acts like i dont have any input values and returns my alert statement with a 0 or a NaN.
MY CODE SO FAR
var input1 = 0;
var input2 = 0;
var again = true;
function main()
{
while (again === true)
{
inputnum1();
inputnum2();
operator();
}
}
function inputnum1()
{
var input1 = 0;
input1 = parseInt(prompt("Input first number: ", "1"));
while ((isNaN(input1)) || (input1 < 1))
{
input1 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
}
}
function inputnum2()
{
var input2 = 0;
input2 = parseInt(prompt("Input second number: ", "1"));
while ((isNaN(input2)) || (input2 < 1))
{
input1 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
input2 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
}
}
function operator()
{
var option = 0;
var string = "";
string += "\nEnter 0 to terminate calculator: ";
string += "\nEnter 1 for addition: ";
string += "\nEnter 2 for subtraction : ";
string += "\nEnter 3 for multiplication: ";
string += "\nEnter 4 for division: ";
string += "\nEnter 5 for modulo/remainder: ";
option = parseInt(prompt(string, "1"));
while ((isNaN(option)) || (option < 0) || (option >5))
{
option = parseInt(prompt(string, "1"));
}
chosenop(option);
}
function chosenop(option)
{
switch (option)
{
case 0:
alert ("Terminated successfully");
again = false;
break;
case 1:
addition();
break;
case 2:
subtract();
break;
case 3:
multiply();
break;
case 4:
divide();
break;
case 5:
modulo();
break;
}
}
function addition()
{
var sum = input1+input2;
alert ("The sum is: " + sum);
}
function subtract()
{
var diff = input1-input2;
alert("The difference is: " + diff);
}
function multiply()
{
var prod = input1*input2;
alert ("The product is: " + prod);
}
function divide()
{
var quot = (input1 + 0.0)/(input2 + 0.0);
alert ("The quotient is: " + quot);
}
function modulo()
{
var mod = input1%input2;
alert ("The modulo is: " + mod);
}
main();
First off, I'd like you to read through this guide.
Now, to your assignment. This line in inputnum2():
input1 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
is superflous.
At the beginning of your code, you have defined variables input1 and input2. However, in inputnum1() and inputnum2() you do var input1 = 0 and var input2 = 0, which limits their scope to the function block. Here's a wikipedia article on scope. So essentially, just remove them.
This is what your code should look like:
var input1 = 0;
var input2 = 0;
var again = true;
function main()
{
while (again === true)
{
inputnum1();
inputnum2();
operator();
}
}
function inputnum1()
{
input1 = parseInt(prompt("Input first number: ", "1"));
while ((isNaN(input1)) || (input1 < 1))
{
input1 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
}
}
function inputnum2()
{
input2 = parseInt(prompt("Input second number: ", "1"));
while ((isNaN(input2)) || (input2 < 1))
{
input2 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
}
}
function operator()
{
var option = 0;
var string = "";
string += "\nEnter 0 to terminate calculator: ";
string += "\nEnter 1 for addition: ";
string += "\nEnter 2 for subtraction : ";
string += "\nEnter 3 for multiplication: ";
string += "\nEnter 4 for division: ";
string += "\nEnter 5 for modulo/remainder: ";
option = parseInt(prompt(string, "1"));
while ((isNaN(option)) || (option < 0) || (option >5))
{
option = parseInt(prompt(string, "1"));
}
chosenop(option);
}
function chosenop(option)
{
switch (option)
{
case 0:
alert ("Terminated successfully");
again = false;
break;
case 1:
addition();
break;
case 2:
subtract();
break;
case 3:
multiply();
break;
case 4:
divide();
break;
case 5:
modulo();
break;
}
}
function addition()
{
var sum = input1+input2;
alert ("The sum is: " + sum);
}
function subtract()
{
var diff = input1-input2;
alert("The difference is: " + diff);
}
function multiply()
{
var prod = input1*input2;
alert ("The product is: " + prod);
}
function divide()
{
var quot = (input1 + 0.0)/(input2 + 0.0);
alert ("The quotient is: " + quot);
}
function modulo()
{
var mod = input1%input2;
alert ("The modulo is: " + mod);
}
main();

Comparing array elements to character

I'm trying to write a simple javascript program to check if a letter is a vowel. The problem is the output is incorrect and should say that " a is a vowel."
Javascript:
function findvowel(letter1, vowels) {
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
}
HTML:
<script>
$(document).ready(function() {
findvowel("a",["a","e","i","o","u"]);
});
</script>
Output:
a is a consonant
Add break to your loop so it doesn't keep going.
function findvowel(letter1, vowels) {
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
break;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
}
You can actually use return false; to stop your function right away when a vowel is matched, however in normal cases break will be used because there might be other codes going on after the loop.
BTW:
function findvowel(letter){
//thanks p.s.w.g for reminding me []
return letter+" is a "+(/[aeiou]/i.test(letter)?"vowel":"constant");
}
You're testing the vowel in the for-loop and updating the output every time. So the output will only display if the last vowel that was tested matched the input. Instead, you should break out of the for-loop if a vowel is found, and only display a failure (" is a consonant") after you've tested all the vowels and you weren't able to find a match:
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
return;
}
}
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
But this method could be simplified to:
function findvowel(letter1) {
var isVowel = "aeiou".indexOf(letter1) > -1;
var message = letter1 + " is a " + (isVowel ? "vowel" : "consonant");
document.getElementById('exercise3').innerHTML = message;
}
This is what I would do, using native functions:
var letter = "a";
var isVowel = ["a","e","i","o","u"].some(function(vowel){
return vowel === letter;
});
Rergarding your message, I would try something like:
var message = letter + (isVowel ? " is a vowel" : " is a consonant");
I would pass in an object instead of an array and take advantage of the constant time lookup using the 'in' keyword. No need for a loop.
function findvowel(letter1, vowels) {
if (letter1 in vowels) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
then
var obj = {'a': true, 'e': true, 'i': true, 'o': true, 'u': true}
then call it
findvowel('a', obj)
Since you're already using jQuery, which offers $.inArray(), why don't you do this?
var vowels = ["a", "e", "i", "o", "u"];
$(document).ready(function() {
var letter = 'u';
var found = $.inArray(letter, vowels) > -1;
if(found) {
console.log(letter + ' is a vowel');
} else {
console.log(letter + ' is a consonant');
}
});

Categories

Resources