ecommerce simulator with JS [closed] - javascript

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 2 days ago.
Improve this question
Can someone please tell me what is wrong with my code? the issue is that when the user is prompted to select the quantity of products desired, it gets stuck there and keeps asking the client the same over again. it does not move forward. Thanks in advance
alert("Please enter the number of the product you would like to purchase. If you are finished, enter '0'.")
let selectedProduct = Number(prompt("1 - Keyboard $80.00, 2 - Electric handle $200.00, 3 - AirPods $300.00, 4 - Watch $100.00"));
let selectedQuantity;
let totalCost = 0;
const calculateCost = (quantity, price) => {
return quantity * price;
};
while (selectedProduct != 0) {
switch(selectedProduct) {
case 1:
selectedQuantity = Number(prompt("You have selected a keyboard. Please enter the quantity you would like to purchase."));
totalCost += calculateCost(selectedQuantity, 80.00);
console.log(totalCost);
break;
case 2:
selectedQuantity = Number(prompt("You have selected an electric handle. Please enter the quantity you would like to purchase."));
totalCost += calculateCost(selectedQuantity, 200.00);
console.log(totalCost);
break;
case 3:
selectedQuantity = Number(prompt("You have selected AirPods. Please enter the quantity you would like to purchase."));
totalCost += calculateCost(selectedQuantity, 300.00);
console.log(totalCost);
break;
case 4:
selectedQuantity = Number(prompt("You have selected a watch. Please enter the quantity you would like to purchase."));
totalCost += calculateCost(selectedQuantity, 100.00);
console.log(totalCost);
break;
default:
alert("Invalid selection. Please try again.");
break;
}
}
alert("Your total purchase amount is: $" + totalCost);

Related

javascript while loop problem,break doesn't stop the loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I built a simple number guessing game with javascript.
After the computer guess the correct answer it should break the loop.
What I am wondering is that even though I break the loop at Line 18
It still execute the code on Line 20(console.log(text)).
The funny thing is that after the break. Only console.log() get executed,L21 & L22 don't do anything,which they are supposed to be that way.
Can't really figure out why. I hope I make the question clear!
Executes last console.log() in repl example
But doesn't in the below snippet (the exact same code)..
let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (true){
let text = `#${i}: computer guess ${guess}.`
if (guess > answer){
text += 'TOO BIG!'
max = guess
} else if (guess < answer){
text += 'TOO Small!'
min = guess
} else{
text += 'win!'
break
}
console.log(text)
guess = Math.floor((max + min) / 2)
i++
}
My guess is that because the REPL tool tries to display a return value for the code you run, it's using the last value before the code exits, which is text += "win!". So it's not actually executing your console.log(text), it just looks like it is.
For example, if you change your code to the following, the REPL tool spits out a number (the value of i before the postfix). Because it's the last value it saw before the while loop exited.
REPL example showing a different "return" value, logging as expected
let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (guess !== answer){
let text = `#${i}: computer guess ${guess}.`
if (guess > answer){
text += 'TOO BIG!'
max = guess
} else if (guess < answer){
text += 'TOO Small!'
min = guess
}
console.log(text)
guess = Math.floor((max + min) / 2)
i++
}
// console.log(`#${i}: computer guess ${guess}. Win!`);
This is not normal JS behavior, and should be taken with a grain of salt when reading "return" values in the REPL tool.Hope this helps!

Using Dynamic data in a Regular Expression [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a list that looks something like this :
listA = ["Physics","English","Chemistry","Biology","History","Human Values","None"]
The web page shows a textArea, where the user can add data like :-
Hello, My fav subject is <<English>>
or
I like <<Biology>> , its the best
I want to show a validation error if the user enters anything else from what in the listA between the <<>>, the rest of message can be anything.
I tried using regular expression but I cant figure it out and I couldn't figure out directives. Please ask if more clarification is required
this is what I have tried so far :
checkText(event) {
// const regex = /(?:^|\s)<<(.*?)>>(?:\s|$)/g;
var str = this.editClauseObj.textObj.text;
console.log("str",str);
let name_val = 'Name';
const regex = /^([a-zA-Z]*\s)*[<<name_val>>]*\s*[a-zA-Z\s]*$/g
if (!regex.test(str)) {
this.showError = true;
this.errorMessage = "Please enter a valid value inside <<>>"
console.log("test", this.showError);
} else {
// do something else
this.showError = false;
}
}
const listA = ["Physics","English","Chemistry","Biology","History","Human Values","None"];
const text = "Hello, My fav subject is <<English>> \n I like <<Biology>> , its the best \n I like <<Hello>> , its the best ";
// Look for << char and then ([^>>]+) except this >> char for 1 and more time and find the next >> char.
const r = /<<([^>>]+)>>/g
let found=[];
while( current_found = r.exec( text ) ) {
found.push( current_found[1] );
}
// all found items in the text
console.log(found);
// filter which is not matching
var final = found.filter(function(item) {
return !listA.includes(item);
});
console.log(final);

Get last "ordered" number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've been struggling with the definition of a function. It must take a positive number N as a parameter and return the last ordered number. By "ordered" number I mean that every digit follow each other.
Example1 : Takes 1000 as a parameter and returns 789.
Example2 : Takes 500 as a parameter and returns 456.
Here's working code. Although I don't like just giving you the answer. This is something you have to practice and learn how to do on your own. Take the time to understand what I did. Also, this solution can be improved a lot, just something that I did quickly and works.
The algorithm in action:
function calc() {
//Get the number in the text input
var nbr = parseInt(document.getElementById("number").value, 10);
//Loop starting from the top
for (var i = nbr; i > 0; i--) {
if (isOrderedNumber(i)) {
document.getElementById("result").innerText = i;
return;
}
}
document.getElementById("result").innerText = "None found";
}
function isOrderedNumber(number) {
var digits = number.toString().split('');
//Loops in the digits of the number
for (var i = 0; i < digits.length - 1; i++) {
//Check if the current number+1 is not equal to the next number.
if (parseInt(digits[i]) + 1 !== parseInt(digits[i + 1])) {
return false;
}
}
return true;
}
<input id="number" type="text" />
<button onclick="calc()">Find last ordered number</button>
<br/>
<br/>
<span id="result"></span>
In you case, instead of using html element you would receive "nbr" by parameter instead and would return the value instead of putting the value in the html element. Ask if you have any questions on how this works.

I was wondering about how I might collect user’s scores for a math quiz I made

I want to collect user’s scores from my GitHub page (theratcoder.github.io). I have used the following JS code (embedded in my HTML document) to create my quiz.
var score = 0;
var times33 = window.prompt("3 x 3");
switch(times33) {
case "9":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var subtract5221 = window.prompt("52 - 21");
switch(subtract5221) {
case "31":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var add56 = window.prompt("5 + 6");
switch(add56) {
case "11":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var divide183 = window.prompt("18 / 3");
switch(divide183) {
case "6":
document.write("correct - ");
score++;
break;
default:
document.write("incorrect - ");
break;
}
var finishing_text;
switch(score) {
case 4:
finishing_text = "Great job!";
break;
case 3:
finishing_text = "Well done.";
break;
case 2:
finishing_text = "Better luck next time!";
break;
case 1:
finishing_text = "You need to work on your math!";
break;
default:
finishing_text = "You really need to work on your math!";
break;
}
var submit = window.confirm("Do you want to submit this quiz?");
var percent = score / 4 * 100;
if (submit) {
document.write("Your final score is " + score + " out of 4 (" + percent + "%). ");
document.write(finishing_text);
}
else {
location.reload();
}
I want to collect the values of the variable “score” so that I can get an idea of how people generally do on my quiz.
In order to do something like that, you'll need two things, a way to get the data to some form of storage, and the storage itself.
Unless some things have changed, github.io sites are static content only, so there's no server running in the background that you can access and communicate with your storage from, just your static content being served by the github.io service and running in the user's browser.
So the basic answer is you can't. But that's not true and there's always a hack if you're willing to do something gnarly. (I assume this is just for fun?)
If that's the case, you could run a server on your computer at home or something. Then when the user answers a question you add a call to the server on your computer at home and it takes that data and saves it and aggregates it however you want.
But end of the day if you want to store things about your users, you're probably going to want to have a dynamic website.
Although, maybe take a look at this if you're determined: https://medium.com/pan-labs/dynamic-web-apps-on-github-pages-for-free-ffac2b776d45 -- it's something like the "send data to your own computer" step, but using the free tier of firebase instead.

javascript simple bmi calculator doesnt work as intended [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
var userweight = prompt ("What is your weight?");
var userheight = prompt ("What is your height in meter?");
var bmi = function (userweight,userheight){
return userweight/(userheight*userheight);
};
var bmi= function(calc){
if(calc<=18.4){
return("you are thin");
}
else if (18.5<=calc<=24.9){
return("you are normal");
}
else if (25.0<=calc<=29.9){
return("you are fat");
}
else if (calc>=30.0){
return("you have obesity");
}
};
bmi(userweight,userheight);
I tried to make a bmi calculator. It calculates your bmi . But it had problems in if/else part. It only shows "You are normal" no matter what bmi it is
At the first, you override the first bmi-formula function assignment with your if/else statements.
You should rename one of these functions:
var userweight = prompt("What is your weight?");
var userheight = prompt("What is your height in meter?");
var formula = function(userweight,userheight){
return userweight / (userheight * userheight);
};
var bmi = function(userweight, userheight){
var calc = formula(userweight, userheight);
if (calc <= 18.4) {
return "you are thin";
}
if (calc >= 18.5 && calc <= 24.9) {
return "you are normal";
}
if (calc >= 25.0 && calc <= 29.9) {
return "you are fat";
}
if (calc >= 30.0) {
return "you have obesity";
}
};
alert( bmi(userweight, userheight) );
The second thing is, that your condition to return the "normal"-part (18.5<=calc<=24.9) is falsey, you could do it like this: calc >= 18.5 && calc <= 24.9. (The same for the "fat"-part)
The last note, as you can see, I've removed the else-keywords since we return a value after if, it doesn't matter what then comes.
You declare the bmi function expression
var bmi = function (userweight,userheight){
return userweight/(userheight*userheight);
};
but the subsequent declaration later on overwrites it completely. So when you call
bmi(userweight, userheight)
Javascript takes the passed in userweight and assigns it to calc. The BMI isn't calculated at all, your first function is never called.
userheight is never used; JavaScript doesn't care if you pass in too many arguments.
Give your functions different names e.g. renaming your first function to calculateBMI and the second one to adviseOnBMI (or whatever you fancy) and rerun it.
console.log is your friend when debugging - use it to output to the Developer Console in your browser of choice.

Categories

Resources