Functions in javascript - beginner question - javascript

Kia ora,
I'm am working on a problem that requires a function and array to be used in the answer. I'm a beginner!! The program needs to ask the user for a number between 1 and 30 that will get translated to either French or German. I've got it all working without using a function. I guess this is a little bit backwards, but now I need to get the function into the code. My understanding of them is beginner level, and there is something that I am missing despite watching countless videos. I'll attach what I have done with comments through it about my thinking. Thanks in advance for your help.
//write function to translate number into choosne language
function translate(number,lang){
//let phrase worked when I had it at the bottom of all the code, ie when there was no function!
let word = lang === "french"? french[number] : german[number];
//relates to function. I think I need tohave the above line return a value, this is what I
think this shold look like
return translatedNumber;
}
//array for French numbers 0-30
let french = ["zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf",
"dix", "onze", "douze", "treize", "quatorze", "quinze", "seize", "dix-sept", "dix-huit", "dix-
neuf", "vingt", "vingt et un", "vingt-deux", "vingt-trois", "vingt-quatre", "vingt-cinq",
"vingt-six", "vingt-sept,", "vingt-huit", "vingt-neuf", "trente"];
//array for German numbers 0-30
let german = ["null", "eins", "zwei", "drei", "vier", "fünf", "sechs", "sieben", "acht",
"neun", "zehn", "elf", "zwölf", "dreizehn", "vierzehn", "fünfzehn", "sechszehn", "siebzehn",
"achtzehn", "neunzehn", "zwanzig", "einundzwanzig", "zweiundzwanzig", "dreiundzwanzig",
"vierundzwanzig", "fünfundzwanzig", "sechsundzwanzig", "siebenundzwanzig", "achtundzwanzig",
"neunundzwanzig", "dreiβig"];
//this block asks for number, gives message if number given is outside scoop. Started with if statement and got forever loop when answer was outside scoop. Changed to while and it works.
let number = prompt ("What number to translate? ");
while (number <= 0 || number > 30) {
alert ("Enter a number between 1 and 30.");
number = prompt ("What number to translate? ");
}
//while statement to ask tranlate langugae wanted. changes answer to lowercase so comparision works regardless of case that the user inputs.
let lang = prompt ("What language to translate? ");
while (lang.toLowerCase() !== "french" && lang.toLowerCase() !== "german") {
alert ("Enter french or german only");
lang = prompt ("What language to translate? ")
}
//I was thinking this would take the answer from the function and then use it in the alert to answer the users question.
let translatedNumber = translate(number, lang);
alert ("The number " + number + " is " + word + " in " + lang);

Easy! just wrap it in a function and call that function!
cut this code into translate()
//array for French numbers 0-30
let french = ["zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf",
"dix", "onze", "douze", "treize", "quatorze", "quinze", "seize", "dix-sept", "dix-huit", "dix-
neuf", "vingt", "vingt et un", "vingt-deux", "vingt-trois", "vingt-quatre", "vingt-cinq",
"vingt-six", "vingt-sept,", "vingt-huit", "vingt-neuf", "trente"];
//array for German numbers 0-30
let german = ["null", "eins", "zwei", "drei", "vier", "fünf", "sechs", "sieben", "acht",
"neun", "zehn", "elf", "zwölf", "dreizehn", "vierzehn", "fünfzehn", "sechszehn", "siebzehn",
"achtzehn", "neunzehn", "zwanzig", "einundzwanzig", "zweiundzwanzig", "dreiundzwanzig",
"vierundzwanzig", "fünfundzwanzig", "sechsundzwanzig", "siebenundzwanzig", "achtundzwanzig",
"neunundzwanzig", "dreiβig"];
it belongs in that method, not outside of it.
finally put this last bit of code in its own method :
function startMethod(){
//this block asks for number, gives message if number given is outside scoop. Started with if statement and got forever loop when answer was outside scoop. Changed to while and it works.
let number = prompt ("What number to translate? ");
while (number <= 0 || number > 30) {
alert ("Enter a number between 1 and 30.");
number = prompt ("What number to translate? ");
}
//while statement to ask tranlate langugae wanted. changes answer to lowercase so comparision works regardless of case that the user inputs.
let lang = prompt ("What language to translate? ");
while (lang.toLowerCase() !== "french" && lang.toLowerCase() !== "german") {
alert ("Enter french or german only");
lang = prompt ("What language to translate? ")
}
//I was thinking this would take the answer from the function and then use it in the alert to answer the users question.
let translatedNumber = translate(number, lang);
alert ("The number " + number + " is " + word + " in " + lang);
}
then at the end, call your function!
startFunction();

Related

Random Fruit guessing Game

I'm in my second week of Javascript and the task we've been given is to create a guessing game.
The steps we've been given are:
Prepare a list of your favourite fruits and store it in an appropriate data structure and have the computer select a random fruit as the secret word.
Base on the selected fruit give the use a hint like the example below. you can use prompt, alert or console.log to show the hint
for example if the secret fruit is "banana"
hint: it's 6 characters long. Starts with b and ends with a. guess the fruit.
instead of typing out the hint manually for every fruit. try to use a template string and programmatically work out the starting letter, ending letter and how many characters long.
Allow the user to guess the fruit repeatedly until they guess correctly. keep track of the number of guesses.
Congratulate the user and display number of attempts they made.
I've been sitting on this for awhile and have tried shifting my code around. I know I'm close but would love some pointers or tips.
This is what I have so far:
var fruits = ["kiwi", "banana", "apple", "strawberry", "watermelon", "orange"];
var ranNum = Math.floor(Math.random() * fruits.length);
var secretFruit = fruits[ranNum];
var userPrompt = prompt("Guess the fruit");
var guess = 1;
while (userPrompt !== secretFruit) {
prompt(
"hint: it's " +
secretFruit.length +
" characters long. Starts with " +
secretFruit[0] +
" and ends with " +
secretFruit.slice(-1) +
". guess the fruit."
);
guess++;
}
if (userPrompt == secretFruit) {
alert(
"Congratulations you guessed the fruit, and it took you " +
guess +
" guesses"
);
}
Any help would be great, thank you.
Two things wrong: your while loop and hint prompt.
First of all, your while loop will continuously keep prompting without ever checking whether the answer was correct, because you have left the if statement outside of the loop.
Also, the if statement should be before the hint statement otherwise the person will always have to try again even if they got the answer correct.
Secondly, your hint prompt is never actually recorded. This means that despite getting the answer correct, the code never actually records it.
Also, I suggest adding a break statement so that the game ends.
This is a working version of your code:
var fruits = ["kiwi", "banana", "apple", "strawberry", "watermelon", "orange"];
var ranNum = Math.floor(Math.random() * fruits.length);
var secretFruit = fruits[ranNum];
var userPrompt = prompt("Guess the fruit");
var guess = 1;
while (userPrompt !== secretFruit) {
if (userPrompt == secretFruit) {
alert(
"Congratulations you guessed the fruit, and it took you " +
guess +
" guesses"
);break; //break statement here stops infinite loop when correct
}
userPrompt = prompt(
"hint: it's " +
secretFruit.length +
" characters long. Starts with " +
secretFruit[0] +
" and ends with " +
secretFruit.slice(-1) +
". guess the fruit."
);
guess++;
}

Trying to make a language translation app

I am trying to make a translation app that can translate a number between 1-30 from english to its german/french counterpart. I think I am somewhat on the right track, ive made the arrays with all the translations, but the problems I am having is I don't know how to correlate the number the user puts in via a prompt, to one of the values in the array, example:
User is prompted for number between 1-30, user is prompted for language French/German = Translation
This is what I am trying to do. Bellow is what I have so far, feel free to nit pick, but bear in mind I am new to Javascript so there is probably a lot wrong.
function translate() {
if (lang = "French") {
console.log(frenchTranslation);
} else {
console.log(germanTranslation);
}
};
var x=translate
translate(x)
var number=(Number(prompt ("What is your number? Must be between 1-30")));
var lang=(prompt ("What is your language? Must be 'French' or 'German'. Case Sensitive."));
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
Right, so first of all, you need to add some input validation to know what the user has selected. I recommend storing it somewhere, then you should make sure that it's in the correct range. Just use an if statement to check if the number is >= 0 && <= 30. After that when you're trying to use console.log you need to use array index of the correct number.
Here's my solution, you can improve on it a lot.
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
function translate()
{
const yournumber = Number(prompt("Enter your number (1-30)"));
console.log(yournumber);
const language = prompt("Choose a language - German or French");
if(yournumber < 1 || yournumber > 30) {
alert("Too hard");
}
else {
if(language === "French") {
console.log(frenchTranslation[yournumber]);
}
if(language === "German") {
console.log(germanTranslation[yournumber]);
}
}
}
translate();

how to detect mobile numbers in a string using javascript

To be honest, this sound like a duplicate post, but this is totally different from other post.
I'm building a chat room, where i would like to detect mobile number in user sending messages and warn the users that sending mobile numbers in the chat room is not safe and its against our policy.
There are few posts shows how to detect US number. But what about Indian numbers? they are 10 digit numbers.
var input = "hey im emily, call me now 9876543210"
I have to detect the number in all these formats.
9876543210
9 8 7 6 5 4 3 2 1 0
98765 43210
+919876543210
+91 9876543210
Some smart users always comes up with a smart way to come around those filters used in the client side javascript. So i have to be well prepared to detect all the method they use.
Example Message :
"hey this is emy, call me now 9876543210"
Expected output : pop up saying, hey buddy, sending numbers in the room is not safe and not allowed here.
Note: The string message should be allowed to send upoto 5 digit numbers, without getting the alert pop up. Or if you have any better idea? suggest me and we can make it work. Thanks
Here's a regex for a 7 or 10 digit number, with extensions allowed, delimiters are spaces, dashes, or periods:
^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
Although you need to add conditions for special numbers like 911, 100, 101
In your test cases the length of phone number is 10:
So try the following code:
let input = "hey im emily, call me now 9 876543210";
let matched = input.match(/\d+/g).join('');
let phoneNumberLength = 10;
if (matched.length >= phoneNumberLength) {
console.log(`we've found a phone number. The number is ${matched}`);
} else
console.log(`The message does not contain phone number`);
Try to adjust this code as it is desired
UPDATE:
This code is intended to get desired results with test case by #tibetty:
let input = 'hi dude, please call my cell phone +86 13601108486 at 300pm"'
let matched = input.split(' ');
let maxIndex = matched.length - 1;
let filtered = matched.filter((s, i) => {
if (i != maxIndex && isNumeric(s) && isNumeric(matched[i + 1]))
return true;
if (isNumeric(s))
return true;
return false;
});
console.log(` The number is found ${filtered.join(' ')}`);
function isNumeric(n) {
return n.match(/^(?:[+\d].*\d|\d)$/);
}
try this one:
https://www.w3resource.com/javascript/form/phone-no-validation.php
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

How can I get a true random from an array? Or should I do something else entirely?

I would like to display a different madlib each time a user clicks the submit button. Only needs to be clicked 3 times. I am using the functions below, but it doesn't seem all that random. I also have a snippet of the dogLib function that creates three madlibs and then calls the function above it to generate a random madlib string.
//Class: madlibGenerator.js
//----- Private Helper Functions -----
//Get Random: word strings for randam madlib
//Get Random: madlib string to display
function getRandomString(array) {
for(var i = array.length - 1; i>0; i--){
var j = Math.floor(Math.random() * (i+1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return this.word = array.pop();
}
//Set: set user input word string arrays into the getRandomString(array)
//Get: a final array of words to add to the madLib display strings
function getFinalWordArray(){
var prpN = getRandomString(this.properNouns);
var adjt = getRandomString(this.adjectives);
var noun = getRandomString(this.nouns);
var vrb = getRandomString(this.verbs);
return finalWordArray = [prpN, adjt, noun, vrb];
}
//Get Random Dog Lib
function getDogLib() {
//Get Random Dog Words
var dogWordsArray = getFinalWordArray();
//DogLibs
var dogLibOne =
"What is that " + dogWordsArray[1] +
" sound!" +
" Hey! " + dogWordsArray[0] +
"! You come " + dogWordsArray[3] +
" you crazy " + dogWordsArray[2] +
"!";
var dogLibTwo =
dogWordsArray[0] + "!! " +
dogWordsArray[0] + "!! " +
"Come " + dogWordsArray[3] +
" and lay on my clean " + dogWordsArray[2] +
" while your treat is still " + dogWordsArray[1] + "!";
var dogLibThree =
"My human comes home and takes me for a " + dogWordsArray[3] +
" where I sit on a " + dogWordsArray[2] +
" and get my " + dogWordsArray[1] +
" belly rubbed!";
//Make array of DogLibs
var dogLibArray = [dogLibOne, dogLibTwo, dogLibThree];
//Pick random dogLib string to display
finalDogLib = getRandomString(dogLibArray);
}
//Display: Random MadLib to console for now
function displayMadlib(pDisplayIDValue) {
if(pDisplayIDValue == "dogLib"){
//display
getDogLib();
console.log(finalDogLib);
}else if(pDisplayIDValue == "loveLib"){
//display
getLoveLib();
console.log(finalLoveLib);
}else if(pDisplayIDValue == "funnyLib"){
//display
getFunnyLib();
console.log(finalFunnyLib);
}
}
The code above isn't broken, it just doesn't produce a true random.
//Preferred Result: the program displays a different madlib each time the user clicks the submit button. The user only needs to click the button 3 times to get different madlibs, the fourth click clears the form and starts the program fresh.
Thank you!
I am open to any idea to make this a truly random madlibGenerator. Maybe counting number of clicks from a submit button?
So true randomness is going to be tough to achieve. Math.Random() from the javascript library isn't truly random as you've guessed, it's pseudo-random, meaning there is a pattern to it over a large number of inputs. Computers inherently can't really do true randomness, because they are always going to have to take some number, perform some sort of algorithm on it (these are usually "Mersenne Twisters" - fun wikipedia read), and spit out the result.
That said, I don't know exactly how to improve on what you've put into place here. With PRNG, a really large number of possible inputs can help a lot. If you want absolutely true randomness, the easiest way would probably be to hook into random.org's API (https://api.random.org/dashboard - developer license is free, limited to 1000 requests per day). Hooking into an API might be more work than you were planning on, but random.org uses (if I remember right) atmospheric noise and barometric pressure from the Earth to create their random numbers, so it's about as close to true randomness as you can possibly get.
I hope this helps!

Trouble with Loop and Functions in Javascript

So i have an assignment and ive been doing it now for a few hours and am very stuck on a few parts of it. So the parts im stuck on is having to use a loop to validate information put into a prompt, and using information from an array to coincide with with a variable in another function and finally displaying all of it.
So I have everything set up but have no idea what exactly im getting wrong here if someone would mind helping point me in the right direction? Oh I should probably mention Im trying to get the second function to go with the array so when the user enters a number (1 through 4) it matches with the prices in the array.
function numSeats() {
//var amountSeat=document.getElementById("price");
var amountSeat=prompt("Enter the amount of seats you would like");
amountSeat=parseInt(amountSeat);
for (i=7; i<amountSeat; i++){
if (amountSeat<1 || amountSeat>6) {
alert("Check the value of " + amountSeat);
location.reload(true);
}else{
alert("Thank You");}
}
return amountSeat;}
function seatingChoice() {
//var seatChoice=document.getElementById("table").innerHTML;
var seatChoice=prompt("Enter the seat location you want.");
seatChoice=parseInt(seatChoice);
for (i=7; i<seatChoice; i++){
if (seatChoice<1 || seatChoice>4) {
alert("Check what you entered for " + seatChoice);
location.reload(true);
}else{
alert("Thank You")}
}
return seatChoice;}
var price=new Array(60, 50, 40, 30);
var name=prompt("Please enter your name.");
if (name==null || name=="")
{
alert("You did not enter a name, try again");
location.reload(true);
}
else
{
alert("Thank You");
}
document.write(name + " ordered " + numSeats() + " for a total dollar amount of " + seatingChoice(
) );
It looks to me like you repeat the same error in both numSeats and seatingChoice;
Let's look at what you're doing with your loop
var amountSeat = prompt("Enter the amount of seats you would like");
for (i=7; i<amountSeat.length; i++) {/* amountSeat[i] */}
prompt asks the client for a String, so amountSeat is a String.
amountSeat.length is thus the number of characters in the String.
You start your loop at i = 7, thus amountSeat[i] starts from the 7th character in the amountSeat (assuming there are at least 7 characters in amountSeat)
It looks to me more like you want to get a number from the prompt;
// string
var amountSeat = prompt("Enter the amount of seats you would like");
// to number
amountSeat = parseInt(amountSeat, 10); // radix of 10 for base-10 input
Next, consider your if
if (amountSeat[i]<1 && amountSeat[i]>6) {
This is saying if less than 1 AND more than 6. No number can be both of these states at the same time, so it will always be false. It looks like you wanted to use an OR, ||
// do your check
if (amountSeat < 1 || amountSeat > 6) { /* .. */ }
Finally, it looks like you want to calculate the price by some logic, which you haven't included. However, I'm sure it will be based upon numSeats and seatingChoice so you will need to keep a reference to these choices.

Categories

Resources