user input - Javascript - javascript

I have a code that I am working on , it is for ordering pizza. I have been coding for 7 days and I want to find out how can I make the pizza prices bigger by the size of the pizza
For example , small pizza is 15.75$ medium is 16.75 and big is 17.75
Each time I run the code , the output is 15.75
(Look at the bottom portion)
employee = confirm("Are you ready to take an order?");
if (employee === true) {
console.log("Here is the order");
} else {
console.log("Ask another employee to take the order. If there is no one, then please take the order ");
}
let orderCount = 0;
const takeOrder = (topping, crustType) => {
orderCount++;
console.log("Order: " + crustType + " pizza topped with " + topping);
};
//
// Order comes here like this - takeOrder('pepperoni', //'texas style');
takeOrder('pepperoni', 'texas style');
//
const getSubTotal = (itemCount) => {
return itemCount * 14.5;
};
//const ^^
console.log("The Sub-Total is " + getSubTotal(orderCount) + "$");
const getTax = (itemCount) => {
return itemCount * 1.25;
};
console.log("The tax is " + getTax(orderCount) + "$");
const getTotal = () => {
return getSubTotal(orderCount) + getTax(orderCount);
};
console.log("And the final total is " + getTotal() + "$");
console.log("Thank you for taking this order.")

As for one of the comments, the price relative to size is not in your logic:
let priceBySize = {
'S': 15.75,
'M': 16.75,
'L': 14.5,
}
// size of order required - might consider also to pass quantity
takeOrder('pepperoni', 'texas style', 'M');
takeOrder('margherita', 'clasic style', 'L');
const getSubTotal = (itemCount, size) => {
return itemCount * priceBySize[size];
};
Also instead of fixed prices for size maybe you'll prefer to have multipliers for sizes and base price per type of pizza.

Related

javascript numbers assignment

i'm having some issues with the final two console.logs of my script. i'm supposed to have numbers output for both but i'm getting NAN
alert("Let's make a shopping list!");
let first = prompt("What is the first item?");
let firstCost = Number(prompt("What is the cost of " + first + "?"));
let firstAmount = Number(prompt("How many of " + first + " would you like?"));
let second = prompt("What is the second item?");
let secondCost = Number(prompt("What is the cost of " + second + "?"));
let secondAmount = Number(prompt("How many of " + second + " would you like?"));
let tax = parseInt(prompt("What is the sales tax for your state?"));
let firstTotal = parseFloat(firstCost * firstAmount);
let secondTotal = parseFloat(firstCost * firstAmount);
let subTotal = parseFloat(firstTotal + secondTotal);
let taxTotal = parseFloat(subTotal * tax);
let grandTotal = parseFloat(subTotal + taxTotal);
console.log(first + " " + firstCost + " " + firstAmount + " " +
firstTotal);
console.log(second + " " + secondCost + " " + secondAmount + " " +
secondTotal);
console.log("tax: " + taxTotal);
console.log("TOTAL: " + grandTotal);
I changed all of the Number() to parseFloat() but I'm not getting the outcome I'm looking for.
Error 1. Copy/paste
This line of code is a mistake:
let secondTotal = parseFloat(firstCost * firstAmount);
You have copied-and-pasted, without changing "first" to "second".
Error 2. You haven't decided whether tax is a percentage or a decimal fraction
You are collecting an INTEGER, i.e. 5% tax will be stored as 5.
But you are using it as though it is a fraction (e.g. 5% represented as 0.05), by just multiplying it by subtotal.
Error 3. When entering data you are using 'cancel' to skip the tax value
This causes it to store NaN in the tax, and that messes up all output that depends on the tax.
Tip. To get answers quickly, get rid of all the code that is irrelevant, and make it runnable within Stack Overflow, using the "<>" icon.
That helps people help you.
let firstCost = Number(prompt("What is the cost of first ?"));
let firstAmount = Number(prompt("How many of first would you like?"));
let secondCost = Number(prompt("What is the cost of second?"));
let secondAmount = Number(prompt("How many of second would you like?"));
// In this next line you are storing an integer (e.g. 5, for 5 percent)
let tax = parseInt(prompt("What is the sales tax for your state?"));
let firstTotal = parseFloat(firstCost * firstAmount);
// This next line is a mistake
// let secondTotal = parseFloat(firstCost * firstAmount);
// You meant this:
let secondTotal = parseFloat(secondCost * secondAmount);
let subTotal = parseFloat(firstTotal + secondTotal);
// But in this line you are treating it as though it is a decimal, e.g. 0.05 for 5 percent.
// let taxTotal = parseFloat(subTotal * tax);
// You probably meant this:
let taxTotal = parseFloat(subTotal * tax/100);
let grandTotal = parseFloat(subTotal + taxTotal);
console.log("tax: " + taxTotal);
console.log("TOTAL: " + grandTotal);

Combine 2 arrays of different lengths and sort date

I have 2 arrays with different lengths
let daysArray = ['09-20', '09-21', '09-22', '09-23', '09-24', '09-25', '09-26']
let weekNameArray = ['Mi', 'Do', 'Fr', 'Sa + So', 'Mo', 'Di' ]
combined them with _.zipWith:
let weakDateArr = _.zipWith(weekNameArray, daysArray , function(first, second) {
return first + " " + second
});
How I can combine them to get the next array:
['Mi 09-20', 'Do 09-21', 'Fr 09-22', 'Sa + So', 'Mo 09-25', 'Di 09-26']
'Sa + So' must be undated *
Hmm, not sure lodash has support for this out of box...
You could apply a simple custom solution using Array.map() and an index offset for the daysArray:
days_offset = 0;
let combined = weekNameArray.map( (name, index) => {
if(name.length <= 2) {
return name + ' ' + daysArray[ index - days_offset ];
} else {
days_offset += 1;
return name;
}
});

If statement in function issue

I can't get the if/else statement in the totalBalance function to work correctly in this code and I'm not sure why.
I have tried switching the greater than to less than and seeing if it solves the outcome but it makes no difference.
jsfiddle link
var moneyAmount = 0;
var food = 0;
var bills = 0;
var total = 0;
moneyAmount = prompt("how much money do you earn per month?");
amountCheck();
document.write("Your balance is " + "£" + moneyAmount + "<br>");
food = confirm("Do you have any food bills?");
if (food === true) {
food = prompt("How much per week?")
document.write("You spend £" + food + " on food per week <br>");
} else {
alert("Lucky!")
};
totalBalance();
/* total = moneyAmount - food; */
console.log("money amount = " + moneyAmount);
console.log("food = " + food);
console.log("total = " + total);
function totalBalance() {
total = moneyAmount - food;
console.log("total is " + total);
if (total > moneyAmount) {
document.write("Your total amount of money per month is £" + total);
console.log("nay");
} else {
document.write("You need to save more money £" + total);
console.log("yay");
};
}
function amountCheck() {
while (isNaN(moneyAmount)) {
alert("Please enter a numeric value");
moneyAmount = prompt("how much money do you have to spend?");
}
}
total will never be more than moneyAmount, because total is moneyAmount - food. So if (total > moneyAmount) will never evaluate as true unless food is a negative value. Not sure what exactly you're going for, but simply changing the if statement to if (total > 0) makes more sense to me given the context.

Declaring variable within functions

Ok, so I I'm having this strange behaviour that I cannot explain. Look at the following:
$("#completeData").on("click", function() {
var toUpdate = {};
var toUpdateCount = 0;
var ratios = {};
This.calculateGradePerSize();
//1) Select all sizes that are equal to NA or are Equal to 0 (means its a new one)
$.each(This.logements, function(key, l) {
if (l.sizeMyId === "NA" || l.sizeMyId === 0) {
toUpdate[l.rueNum] = l;
toUpdateCount++;
} else { //else init the ratios because it means they are actually present
/**
//My problem is this variable,
I want it to be equal to an empty object
But for reasons I cannot seem to understand,
it takes in account the latter modification in the code
that happens to this variables
*/
ratios[l.sizeMyId] = {};
}
});
console.log(toUpdate);
console.log(ratios);
console.log(This.sizeRatio);
//2) Calculate Ratios and build the ratios function of the toUpdate
$.each(This.sizeRatio, function(sizeMyId, count) {
if (sizeMyId !== "NA" && sizeMyId != 0) {
console.log("COUNT SIZE: " + count + " COUNT LOGEMENT: " + This.countLogement + " toUpdateCount: " + toUpdateCount + " SizeMyId: " + sizeMyId);
console.log("Calculation: " + count / This.countLogement * toUpdateCount);
ratios[sizeMyId].count = Math.ceil(count / This.countLogement * toUpdateCount);
console.log("Calculation WITH CEIL: " + Math.ceil(count / This.countLogement * toUpdateCount));
ratios[sizeMyId].grade = This.sizeGrade[sizeMyId];
ratios[sizeMyId].sizeMyId = sizeMyId;
}
});
console.log(ratios);
});
As explained in the multiline comment, my problem is the ratio variable. I tried declaring the variable without var prefix, so that JS doesn't know its existence but still, I want it to be empty object. In fact, the problem has stronger roots than simply that, I cannot update it. Each change I make to the ratios var are not registered, but I wanna start with the beginning how can I make sure that this variable is empty at the beginning of the function.
I don't know if this question is really worth. Thinking about deleting it. My bug was that the count variable in the each function as well as the ratio definition were the same hence not registering.
As for the variable not being an empty one at function start. It simply how the JS engine works. If there is something not working, more likely than not, there is something wrong in your code.
$.each(This.sizeRatio, function (sizeMyId, count) {
if (sizeMyId !== "NA" && sizeMyId != 0) {
console.log("COUNT SIZE: " + count + " COUNT LOGEMENT: " + This.countLogement + " toUpdateCount: " + toUpdateCount + " SizeMyId: " + sizeMyId);
console.log("Calculation: " + count / This.countLogement * toUpdateCount);
//HERE ratios[sizeMyId].count IS THE SAME than the anonymous function.
ratios[sizeMyId].count = Math.ceil(count / This.countLogement * toUpdateCount);
console.log("Calculation WITH CEIL: " + Math.ceil(count / This.countLogement * toUpdateCount));
ratios[sizeMyId].grade = This.sizeGrade[sizeMyId];
ratios[sizeMyId].sizeMyId = sizeMyId;
}
});

JS function that returns decimal format 1

I have written a function to_money so that 'Price' 'Quantity' and 'Total' in the sub_total function are formatted and two zeroes attached - so 2 becomes 2.00, the function is here:
to_money: function(amount) {
return Number(amount).toFixed(2)
},
sub_total: function() {
var In = this
return $$('.item').inject(0, function(sum, row) {
var quantity = Number($F('Item' + row.id + 'Quantity'))
var price = Number($F('Item' + row.id + 'Price'))
var line_total = quantity * price
$('Item' + row.id + 'Quantity').value = In.to_money(quantity)
$('Item' + row.id + 'Price').value = In.to_money(price)
$('Item' + row.id + 'Total').update('£' + In.to_money(line_total)) In.to_money(line_total))
return sum + line_total
})
How do I write a function that is similar to the function 'to money' that formats the price, but instead a function that formats the quantity for making sure a default decimal of 1 is prefixed to the quantity if no input is entered.
so the line in function sub_total would call the the new function to run on quantity:
$('Item' + row.id + 'Quantity').value = In.to_decimal(quantity)
Would the function look like this?
to_decimal: function(amount) {
return Number(amount).toFixed(0)
},
try
to_decimal: function(amount) {
var n = Number(amount);
return (n && n>0 ? n : 1).toFixed(2);
}
In.to_decimal(''); //=> 1.00
In.to_decimal('bogusinput'); //=> 1.00
In.to_decimal(0); //=> 1.00
In.to_decimal('23.1'); //=> 23.10
//note: Number autotrims the parameter
In.to_decimal(' 45.3'); //=> 45.30

Categories

Resources