Openweathermap API won't work outside of VS Code - javascript

I'm still new to API's but for the life of me I can't figure out why this app works fine when viewing it on live-server in Visual Studio Code, but won't work anywhere else!
I'm still SUPER new to coding, and this is my first time using API's. Do I need to create a CRUD operation?
I posted the js file below.
let appId = 'fa19585e62ed3b8595ff01cd2670cfd2'
let units = 'imperial'
let searchMethod;
function getSearchMethod(searchTerm) {
if(searchTerm.length === 5 && Number.parseInt(searchTerm) + "" === searchTerm)
searchMethod = 'zip'
else
searchMethod = 'q'
}
function searchWeather(searchTerm) {
getSearchMethod(searchTerm)
fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`).then(result => {
return result.json()
}).then(result => {
init(result)
})
}
function init(resultFromServer) {
switch (resultFromServer.weather[0].main) {
case 'Clear':
document.body.style.backgroundImage = 'url("clear.jpg")'
break;
case 'Clouds':
document.body.style.backgroundImage = 'url("cloudy.jpg")'
break;
case 'Rain':
case 'Drizzle':
case 'Mist':
document.body.style.backgroundImage = 'url("rain.jpg")'
break;
case 'Thunderstorm':
document.body.style.backgroundImage = 'url("storm.jpg")'
break;
case 'Snow':
document.body.style.backgroundImage = 'url("snow.jpg")'
break
default:
break;
}
let weatherDescriptionHeader = document.getElementById('weatherDescriptionHeader')
let temperatureElement = document.getElementById('temperature')
let humidityElement = document.getElementById('humidity')
let windSpeedElement = document.getElementById('windSpeed')
let cityHeader = document.getElementById('cityHeader')
let weatherIcon = document.getElementById('documentIconImg')
weatherIcon.src = 'http://openweathermap.org/img/w/' + resultFromServer.weather[0].icon + '.png'
let resultDescription = resultFromServer.weather[0].description
weatherDescriptionHeader.innerText = resultDescription.charAt(0).toUpperCase() + resultDescription.slice(1)
temperatureElement.innerHTML = Math.floor(resultFromServer.main.temp) + '&#176 '
windSpeedElement.innerHTML = 'Wind at ' + Math.floor(resultFromServer.wind.speed) + ' m/s'
cityHeader.innerHTML = resultFromServer.name
humidityElement.innerHTML = 'Humidity levels at: ' + resultFromServer.main.humidity + '%'
setPositionForWeatherInfo()
}
function setPositionForWeatherInfo() {
let weatherContainer = document.getElementById('weatherContainer')
let weatherContainerHeight = weatherContainer.clientHeight
let weatherContainerWidth = weatherContainer.clientWidth
weatherContainer.style.left = `calc(50% - ${weatherContainerWidth/2}px)`
weatherContainer.style.top = `calc(50% - ${weatherContainerHeight/1.3}px)`
weatherContainer.style.visibility = 'visible'
}
document.getElementById('searchBtn').addEventListener('click', () => {
let searchTerm = document.getElementById('searchInput').value
if(searchTerm)
searchWeather(searchTerm)
})

It looks like you might have some issues with your code because you're asking for data over HTTP instead of HTTPS
Refer to the following MDN page:
If your website delivers HTTPS pages, all active mixed content delivered via HTTP on this pages will be blocked by default. Consequently, your website may appear broken to users (if iframes or plugins don't load, etc.). Passive mixed content is displayed by default, but users can set a preference to block this type of content, as well.

Change URL in searchWeather from http://api.openweathermap.org/... to https://api.openweathermap.org/...

Related

how to get the fetch method to work and the process after linking external data source?

i am a beginner at javascript, and i'm asked to build a dynamic image galleries with external data using the fetch() method for an assignment. the requirement for this is to use the fetch() method to link an image slider onto this main page, and i need to make a button to click where a random number is chosen and an external dataset is loaded. but i am having difficulty getting the code to work and i don't know how or where the mistake is, this code is given to me as an example and i need to revise it with my own external links. please help me!
this is what i have in javascript:
console.clear();
document.querySelector("button#myLanguageBTN").addEventListener(
"click",
function () {
var randomNumber = Math.floor(Math.random() * 5);
switch (randomNumber) {
case 1:
var myfetchLink = "https://codepen.io/tchau16/pen/PoaaJYG.js";
case 2:
var myfetchLink = "https://codepen.io/tchau16/pen/dyKKVGP.js";
case 3:
var myfetchLink = "https://codepen.io/tchau16/pen/jOKKGWZ.js";
case 4:
var myfetchLink = "https://codepen.io/tchau16/pen/JjZZrGQ.js";
default:
var myfetchLink = "https://codepen.io/tchau16/pen/dyKKVGP.js";
}
console.log(myfetchLink);
.then((response) => {
return response.text();
})
.then((myInformation) => {
const myReturn = JSON.parse(myInformation);
There are few mistakes in your code -
switch does not have a break statement, so it was falling to default statement every time.
Fetch was not used. Added console logs at appropriate places.
use let and const, removed var for myfetchLink.
use free apis to test your code.
Switch JS MDN link - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Free apis - https://apipheny.io/free-api/#apis-without-key
console.clear();
document.querySelector("button#myLanguageBTN").addEventListener(
"click",
function() {
let randomNumber = Math.floor(Math.random() * 5);
let myfetchLink = '';
switch (randomNumber) {
case 1:
myfetchLink = "https://www.boredapi.com/api/activity";
break;
case 2:
myfetchLink = "https://catfact.ninja/fact";
break;
case 3:
myfetchLink = "https://api.publicapis.org/entries";
break;
case 4:
myfetchLink = "https://codepen.io/tchau16/pen/JjZZrGQ.js";
break;
default:
myfetchLink = "https://api.coindesk.com/v1/bpi/currentprice.json";
}
console.log(myfetchLink);
fetch(myfetchLink)
.then((response) => {
console.log(response);
return response.text();
}).then((myInformation) => {
console.log(myInformation);
const myReturn = JSON.parse(myInformation);
});
});
<button id="myLanguageBTN">Fetch the Data</button>

Better way of searching specific keywords in strings in JavaScript

I am working with an array of urls and for each url i wanna find a image corresponding to the site domain. my first attempt was
const url = new URL(props.url);
const platform = url.hostname.split(".")[1];
console.log(platform)
const platform_logos = {
"codechef": "images/chef.png",
"withgoogle": "images/google.png",
.
.
.
"codeforces": "images/codeforces.png",
}
let platform_logo = platform_logos[platform];
but it doesnt work with url of type 'https://momo2022fr.hackerearth.com' so i had to resort to
let platform_logo = "images/code.png"
if (url.includes("hackerearth")) {
platform_logo = "images/hackerearth.png"
}
else if (url.includes("hackerrank")) {
platform_logo = "images/hackerrank.png"
}
else if (url.includes("codeforces")) {
platform_logo = "images/codeforces.png"
}
else if (url.includes("codechef")) {
platform_logo = "images/chef.png"
}
else if (url.includes("atcoder")) {
platform_logo = "images/atcoder.png"
}
else if (url.includes("leetcode")) {
platform_logo = "images/leetcode.png"
}
else if (props.url.includes("withgoogle")) {
platform_logo = "images/google.png"
}
Is there any better way of writing the code below, it just feels like it violates DRY
You could change how you're reading the url to only get the root domain.
location.hostname.split('.').reverse().splice(0,2).reverse().join('.').split('.')[0]
This code would give hackerearth for https://momo2022fr.hackerearth.com/.
So there are several ways of achieving this.
These are just two from the top of my head.
Parsing the url and using a switch() to determine the outcome, with fallback if none is found.
const url = new URL("https://www.withgoogle.com/search?q=test");
const sites = [
"hackerearth",
"hackerrank",
"codeforces",
"codechef",
"atcoder",
"leetcode",
"withgoogle",
];
console.info(url.hostname);
const site = url.hostname.match(new RegExp(`${sites.join("|")}`));
let logo = "";
switch (site[0]) {
case "hackerearth":
logo = "images/hackerearth.png";
break;
case "hackerrank":
logo = "images/hackerrank.png";
break;
case "codeforces":
logo = "images/codeforces.png";
break;
case "codechef":
logo = "images/chef.png";
break;
case "atcoder":
logo = "images/atcoder.png";
break;
case "leetcode":
logo = "images/leetcode.png";
break;
case "withgoogle":
logo = "images/google.png";
break;
default:
logo = "images/code.png";
break;
}
console.info(logo);
Then there is the modern way, with less code and programming the fallback.
// const url = new URL("https://eee.com/test");
const url = new URL("https://www.withgoogle.com/search?q=test");
const sites = {
hackerearth: "images/hackerearth.png",
hackerrank: "images/hackerrank.png",
codeforces: "images/codeforces.png",
codechef: "images/chef.png",
atcoder: "images/atcoder.png",
leetcode: "images/leetcode.png",
withgoogle: "images/google.png",
default: "images/code.png",
};
let site = url.hostname.match(new RegExp(`${Object.keys(sites).join("|")}`));
if (site === null) {
site = "default";
}
console.info(site, sites[site]);
You could just do the same thing as in your first solution and store the mapping from the substring to the image path in an ocject:
const platform_logos = {
"hackerearth": "images/hackerearth.png",
"hackerrank": "images/hackerrank.png",
"codeforces": "images/codeforces.png",
"codechef": "images/chef.png",
"atcoder": "images/atcoder.png",
"leetcode": "images/leetcode.png",
"withgoogle": "images/google.png"
};
Then you could iterate over the key-value pairs in your object to find the key that is part of the URL and return it once it matches:
function getLogo(url) {
for(const [key, value] of Object.entries(platform_logos)) {
if(url.contains(key)) {
return value;
}
}
}
let platform_logo = getLogo(url);
You can iterate over the images and check URL:
const url = "https://example.com/codechef/asdasd/...";
const platform_logos = {
"codechef": "images/chef.png",
"withgoogle": "images/google.png",
"codeforces": "images/codeforces.png",
}
let img = "default.png";
for (const [key, value] of Object.entries(platform_logos)) {
if (url.includes(key)) {
img = value;
break;
}
}
console.log(img);

I want to read a certain amount of lines from a text file, and with them to create an object after reading the lines using JavaScript

okay, so this is my requirement: The application must read each line from the text file. A class can be used so that after reading a certain number of lines an object is created (in this way the application is more clearly structured). After reading a data set that corresponds to a student's data, it will add this data set to a string (separate so that it is presented in consecutive rows).
So i have these information of 2 students which are one under the other like in the picture below but without the name address etc.(it doesn't show quite right in here).
Ebonie Rangel
7175 Yukon Street
(507) 833-3567
Geography
Keenan Ellwood
2 Elm Lane
(894) 831-6482
History
which are in that file. and after reading every line, I am supposed to add Name in front of the first line, Address in front of the second.. phone and Course and so on.
The result should look like this:
This is what i have for now (I have to use Fetch to get to the file, async and await. or with Promise)
let button = document.getElementById("text-button");
let textArea = document.getElementById("text-area");
button.addEventListener("click", function () {
getData();
});
//cod fetch
async function getData() {
try {
let response = await fetch('fileName.txt');
if (response.status !== 200) {
throw new Error("Error while reading file");
}
let text = await response.text();
textArea.innerHtml = text;
} catch (err) {
textArea.innerHTML = 'Problem occurred: ' + err.message;
}
}
please help! I am stuck since forever on this.
Since you're pulling from a .txt file I think its important to understand the line breaks being used in the file. Here's a decent link I found that says all you need at the top of the article: End of Line or Newline Characters
I opened up the .txt file in Notepad++ like the article recommended and saw this:
The [CR][LF] being displayed after each line means that the newline characters used are \r\n.
When you understand that you realize you can use those line breaks to separate your string at each line break.
Here's the MDN for String.split() String.prototype.split()
String.split('\r\n') will return an Array of items, specifically the strings that were between but not including the \r\n characters.
Let's add this to the getData function:
let button = document.getElementById("text-button");
let textArea = document.getElementById("text-area");
button.addEventListener("click", function () {
getData();
});
//cod fetch
async function getData() {
try {
let response = await fetch('fileName.txt');
if (response.status !== 200) {
throw new Error("Error while reading file");
}
let text = await response.text();
//New stuff:
let arrayOfText = text.split('\r\n');
//Now we could add what we want before the text.
//We need to do every 4 lines so lets use this as a chance to learn % better
arrayOfText = arrayOfText.map((textItem, index) => {
let remainder = (index) % 4 //This will return 0, 1, 2, 3
//switch but you could use anything
switch (remainder) {
case 0:
textItem = 'Name: ' + textItem + '\r\n';
break;
case 1:
textItem = 'Address: ' + textItem + '\r\n';
break;
case 2:
textItem = 'Phone: ' + textItem + '\r\n';
break;
case 3:
textItem = 'Course: ' + textItem + '\r\n\r\n'; //two here to separate the groups
break;
//we need a default so lets make it just return textItem if something goes wrong
default:
break;
};
//Our new array has all the info so we can use
//Array.prototype.join('') with an empty string to make it a string.
//We need those old line breaks though so lets put them
//in the switch returns above.
text = arrayOfText.join('');
//End of my changes/////////////
textArea.innerHtml = text;
} catch (err) {
textArea.innerHTML = 'Problem occurred: ' + err.message;
}
}
I hope this works out for you. Its not the most glamorous solution but its a good learning solution because it uses only things you learn early on in your studies.
Let me know if I can clarify anything!
async function getData() {
try {
let response = await fetch('https://v-dresevic.github.io/Advanced-JavaScript-Programming/data/students.txt');
if (response.status !== 200) {
throw new Error("Error while reading file");
}
let text = await response.text();
const lines = text.split('\n');
const CHUNK_SIZE = 4;
textArea.innerHTML = new Array(Math.ceil(lines.length / CHUNK_SIZE))
.fill()
.map(_ => lines.splice(0, CHUNK_SIZE))
.map(chunk => {
const [Name, Address, Phone, Course] = chunk;
return {Name, Address, Phone, Course};
})
.reduce((text, record) => {
text += Object.keys(record).map(key => `${key} ${record[key]}`).join('\n') + '\n';
return text;
}, '');
} catch (err) {
textArea.innerHTML = 'Problem occurred: ' + err.message;
}
}

Chrome Extension Dev. (typescript) - "TypeError: o is not a function" ONLY when opening new tab and setting storage.local to "true"

I've been developing a scraper-type chrome extension for internal/personal use to scrape course data from a university's website.
The high-level algorithm is as follows:
Open up the main page where the user can input the class data they want to find. (The point is to use the data in this page to generate every possible url for every unique course page)
Generate the first endpoint and open a new tab with that url. (This is what I'm calling the "second degree scrape")
Begin the second degree scrape and when it's done, set the chrome.storage.local to true. Then close the tab.
The content script from the main page reads the local storage and sees that the state is true so it resolves the promise. It resets the local storage to false.
It generates the new url and recursively repeats the process until every possible url is created.
The extension works well when I set the storage true and never modify it and simply console.log every possible url. The error arrises when I let the program open up a new tab and let it update local.storage. Before using local.storage I tried a similar implementation using messaging (simple and long-lived) and background but I had the same issue then.
Any ideas of what I could try?
Here's my code:
background/index.ts
chrome.storage.local.set({ secondDegreeState: false });
content/index.ts
const un:string = "***";
const pw:string = "***"
const levels:Array<string> = ['L', 'U', 'G'];
let ccyys:string = `20212`;
let search_type_main:string = `FIELD`
let signInSequence:Function = () => {
if(document.getElementById("login-button")){
let signInButton:HTMLInputElement = document.getElementById("login-button")?.children[0] as HTMLInputElement;
let username: HTMLInputElement = document.getElementById("username") as HTMLInputElement;
let password: HTMLInputElement = document.getElementById("password") as HTMLInputElement;
username.value = un;
password.value = pw;
signInButton.value = "Begin Scraping";
setTimeout(() => {
signInButton.click();
console.log('Sign in button pressed');
}, 2000);
}
}
let scrapingSeqence:Function = () => {
if(window.location.href === "https://utdirect.utexas.edu/apps/registrar/course_schedule/20212/"){ // If we are in the main registration page
firstDegreeScrape(0, 1);
}
if(window.location.hostname == "utdirect.utexas.edu"){ // Make sure that we're on a proper hostname
secondDegreeScrape();
}
}
function secondDegreePromise(url:string) : Promise<any> {
/// Open up a new tab with the generated URL
window.open(url, '_blank');
return new Promise (function callback(resolve:Function, reject:Function) {
chrome.storage.local.get(['secondDegreeState'], (response) => {
if(chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
reject("Chrome error");
}else if (response.secondDegreeState === false){ // If the second degree state is still not done
console.log('Still waiting for 2nd degree scrape to finish...'+' Its state is '+response.secondDegreeState);
setTimeout(callback, 5000); // repeat promise after n-seconds until state is true.
}else if(response.secondDegreeState === true){ // If the promise is complete
resolve("2nd degree scrape was complete!");
}else {
reject("Oopsie...");
}
})
});
}
// Two base cases, 1: it reaches the end of the levels array, 2: it reaches the end of the FOS list.
let firstDegreeScrape:Function = (levelNum: number, fosNum: number) => {
// Reset the scrape state (Turns it false)
chrome.storage.local.set({ secondDegreeState: false });
if (levelNum < levels.length){ // If not base case #1
const fosParent:HTMLElement|null = document.getElementById("fos_fl"); // Define the FOS parent element.
if(fosParent){ // If the fosParent is present. (Will most likely return true... just for extra safety)
let fosChildren = fosParent.children;
if(fosNum < fosChildren.length){ // If not base case #2
let fos:HTMLOptionElement = fosChildren[fosNum] as HTMLOptionElement; // The individual field of study.
let fosValue:string = fos.value.split(' ').join('+'); // Format FOS
const url:string = `https://utdirect.utexas.edu/apps/registrar/course_schedule/20212/results/?ccyys=${ccyys}&search_type_main=${search_type_main}&fos_fl=${fosValue}&level=${levels[levelNum]}`;
secondDegreePromise(url)
.then((res)=>{ // If the second degree scrape promise is resolved
console.log(res+"Now moving along to next URL.");
firstDegreeScrape(levelNum, fosNum+1); // Generate the next URL and scrape it
})
.catch(res=>{console.log(res)});
}else {
firstDegreeScrape(levelNum+1, 1);
}
}
}
}
let secondDegreeScrape:Function = () => {
// make sure that there is something to scrape
let table: HTMLTableElement = document.getElementsByClassName('rwd-table')[0] as HTMLTableElement;
if(table){
let t_rows:HTMLCollection = table.children[1].children as HTMLCollection;
let t_rows_arr:Element[] = Array.from(t_rows);
for(let i=0; i < t_rows_arr.length; i++){
// console.log(t_rows_arr[i].childElementCount);
if(t_rows_arr[i].childElementCount == 1){ // If the row is a title
let course_title:any = t_rows_arr[i].childNodes[1].firstChild?.firstChild?.textContent;
let divisionRegex = /^[a-z\s]{0,3}/gi;
let courseNumRegex = /\d*\w/m;
console.log("Division: "+course_title.match(divisionRegex)[0]);
course_title = course_title.replace(divisionRegex, "");
console.log("Course Number: "+course_title.match(courseNumRegex)[0]);
course_title = course_title.replace(courseNumRegex, "");
console.log("Course Name: "+course_title);
}else { // If it's a sub-column
let row = t_rows_arr[i];
let rowChildren = row.childNodes;
let unique = rowChildren[1].childNodes[0].childNodes[0].textContent; //
console.log("Unique: "+unique);
let days = rowChildren[3].textContent;
console.log("Days: "+days);
let hour = rowChildren[5].textContent;
console.log("Hour: "+hour);
// let room;
let instruction_mode = rowChildren[9].textContent;
console.log("Instruction Mode: "+instruction_mode);
let instructor = rowChildren[11].textContent;
console.log("Instructor: "+instructor);
let status = rowChildren[13].textContent;
console.log("Status: "+status);
let flags = rowChildren[15].textContent;
console.log("Flags: "+flags);
let core = rowChildren[17].textContent;
console.log("Core: "+core);
console.log("\n");
}
}
if(document.getElementById("next_nav_link")){ // If there is a next page
setTimeout(()=>{
document.getElementById("next_nav_link")?.click(); // Click the next button
}, 5000)
}else {
setTimeout(()=>{
// Let's complete the 2nd degree scrape (Sets true) & update the local variable
chrome.storage.local.set({ secondDegreeState: true });
//close the tab
window.close();
}, 1000)
}
}
}
let main:Function = () => {
signInSequence();
scrapingSeqence();
}
main();
manifest.json permissions:
tabs
declarativeContent
storage
activeTab
Thanks for the help!

Javascript While Loop Error with User Input

I am just beginning with JS and am having trouble with scope and executing code in similar style as I would with Python. I have started learning JS on Codecademy and have just begun my first project.
My code for the project is below:
//////////////////////////
// R U Hungry Console App
/////////////////////////
// Step 1: Load in Necessary Modules
////////////////////////////////////
// add in the prompt-sync module
// allows to take in and display users name
const prompt = require('prompt-sync')();
// load in fs module
// allows reading in from text files
const fs = require("fs");
// load open module
//allows the opening of webpages
const open = require('open');
// Step 2: Create a menu object
///////////////////////////////
const menu = {
starters: [],
mains: [],
desserts: []
}
// Step 3 Create a factory function to update the Menu object
/////////////////////////////////////////////////////////////
const menuUpdate = (course,dishName,dishLink) => {
if (course.toLowerCase() === 'starter'){
let newItem = {dish: dishName, link: dishLink};
menu.starters.push(newItem);
} else if (course.toLowerCase() === 'main'){
let newItem = {dish: dishName, link: dishLink};
menu.mains.push(newItem);
} else if (course.toLowerCase() === 'dessert'){
let newItem = {dish: dishName, link: dishLink};
menu.desserts.push(newItem);
} else {
console.log('You did not enter a valid course.\nCould not update menu');
}
}
// Step 4: Read in text files of scraped web data
/////////////////////////////////////////////////
const dishes = [menu.starters,menu.mains,menu.desserts];
const filesToRead = ['starters.txt','mains.txt','desserts.txt'];
function addFiles(course,file){
const text = fs.readFileSync(`./menu_files/${file}`);
const textByLine = text.toString().split("\n");
for (const line of textByLine){
course.push(line);
}
}
addFiles(dishes[0],filesToRead[0]);
addFiles(dishes[1],filesToRead[1]);
addFiles(dishes[2],filesToRead[2]);
// Step 5: Put it all together
//////////////////////////////
console.log('\n\nFeeling hungry and can\'t decide what to eat? You have come to the right place.')
const name = prompt('What is your name? ');
console.log(`\nWelcome, ${name}!\nWould you like to be:\n1.Presented With a Menu\n2.Add a Dish to the Menu`);
let userChoice;
while (true){
userChoice = prompt('\nEnter 1 to get a Menu\nEnter 2 to add a Menu Item\nEnter 3 to exit R U Hungry ');
if (userChoice.trim() === 1){
const starterSelector = Math.floor(Math.random() * menu.starters.length);
const mainSelector = Math.floor(Math.random() * menu.mains.length);
const dessertSelector = Math.floor(Math.random() * menu.desserts.length);
let starterDish = menu.starters[starterSelector][0];
let starterRecipe = menu.starters[starterSelector][1];
let mainDish = menu.mains[mainsSelector][0];
let mainRecipe = menu.mains[mainsSelector][1];
let dessertDish = menu.desserts[dessertSelector][0];
let dessertRecipe = menu.desserts[dessertSelector][1];
console.log(`${name}, your Menu is as follows:\n`);
console.log(`Starter: ${starterDish}`);
console.log(`Main: ${mainDish}`);
console.log(`Dessert: ${dessertDish}`);
console.log('\nWe will direct you to recipes for your selected dishes');
// opens the url in the default browser
open(starterRecipe);
open(mainRecipe);
open(dessertRecipe);
} else if (userChoice.trim() === 2){
let userCourse = prompt('Is your dish a Starter, Main or Dessert? ');
let userDishName = prompt('Great! Please tell me the name of your dish ');
let userDishLink = prompt('Please provide the link to the dish recipe ');
menuUpdate = (userCourse,userDishName,userDishLink);
console.log('Menu updated with your dish!');
} else {
console.log(`Goodbye, ${name}.`);
break;
}
console.log('Would you like to perform another function?');
}
// End
I am having trouble with the while loop at the end.
This part specifically:
let userChoice;
while (true){
userChoice = prompt('\nEnter 1 to get a Menu\nEnter 2 to add a Menu Item\nEnter 3 to exit R U Hungry ');
if (userChoice.trim() === 1){
const starterSelector = Math.floor(Math.random() * menu.starters.length);
const mainSelector = Math.floor(Math.random() * menu.mains.length);
const dessertSelector = Math.floor(Math.random() * menu.desserts.length);
let starterDish = menu.starters[starterSelector][0];
let starterRecipe = menu.starters[starterSelector][1];
let mainDish = menu.mains[mainsSelector][0];
let mainRecipe = menu.mains[mainsSelector][1];
let dessertDish = menu.desserts[dessertSelector][0];
let dessertRecipe = menu.desserts[dessertSelector][1];
console.log(`${name}, your Menu is as follows:\n`);
console.log(`Starter: ${starterDish}`);
console.log(`Main: ${mainDish}`);
console.log(`Dessert: ${dessertDish}`);
console.log('\nWe will direct you to recipes for your selected dishes');
// opens the url in the default browser
open(starterRecipe);
open(mainRecipe);
open(dessertRecipe);
} else if (userChoice.trim() === 2){
let userCourse = prompt('Is your dish a Starter, Main or Dessert? ');
let userDishName = prompt('Great! Please tell me the name of your dish ');
let userDishLink = prompt('Please provide the link to the dish recipe ');
menuUpdate = (userCourse,userDishName,userDishLink);
console.log('Menu updated with your dish!');
} else {
console.log(`Goodbye, ${name}.`);
break;
}
console.log('Would you like to perform another function?');
}
It keeps executing the code in the else block and then exiting the program.
In python I would have used something like this:
while (True):
choice = input("What is your name? ")
if choice.strip().lower() != 'john':
print("Who are you?")
break;
elif choice choice.strip().lower() != 'shaun':
print("Who are you?")
break;
else:
print("Hi there, glad you aren't John or Shaun")
continue
Stupid example but I just wanted to show how I could normally have achieved something like this before.
Would anyone be able to explain what is incorrect?
I also struggle to understand the scope in JS. Is that perhaps the problem here?
I am finding it difficult in some cases to apply my thinking from Python to JS.
Any help would be appreciated. I am really wanting to learn.
Thanks!
Maybe as a starter you can you == rather than === as it would not match the type, also in your else if it seems you are calling function incorrectly, remove =.

Categories

Resources