Can you help point out what is wrong with my code here:
The goal is to to compute the total amount spent by a diner party of 3 people, each ordering 2 dishes.
I know there are other ways to do this using 'this' and 'new' in a more oop manner, but I think my approach here is more readable..if I can make it work. The code works fine if each patron only orders 1 dish so there is something wrong with the way I have been trying to access the JS dictionary.
Sorry about the newbie question. Any help is appreciate!
var diners=[
{name:'adam', entree1:'ramen', price1:11.5, entree2: 'miso', price2 : 3},
{name:'bobby', entree1: 'udon', price1 :10.69, entree2: 'gyoza', price2 :4.5},
{name:'carly', entree1: 'teriyaki chicken', price1:12, entree2: 'miso', price2 : 3},
];
var entrees1_total=0;
for (var d in diners){
entrees1_total += diners[d].price1; //total expense of entree1 for all diners
diners[d].tax1 = diners[d].price1*0.082; // method for sales tax
entrees1_total += diners[d].tax1; //total entree1 price including sales tax
}
var entrees2_total=0;
for (var d in diners){
entrees2_total += diners[d].price2;
diners[d].tax2 = diners[d] * price2 * 0.082;
entrees2_total += diners[d].tax2;
}
var total = entree1_total + entree2_total;
var total_bill = total*1.2; //tips
console.log("total is: " + total_bill.toString());
for (var d in diners) {
console.log(diners[d].name + " spends " + (diners[d].price1 + diners[d].tax1)+(diners[d].price2 + diners[d].tax2));
} // print out total spent for each patron
You can just use .reduce() to iterate the array and keep a running total:
var rawTotal = diners.reduce(function(cum, obj) {
return cum + obj.price1 + obj.price2;
}, 0);
// add in tax and tip
var tax = rawTotal * 0.082;
var tip = rawTotal * 0.2; // assumes you don't include taxes in tip calculation
var finalTotal = rawTotal + tax + tip;
Working demo: https://jsfiddle.net/jfriend00/ure3r2jg/
A few notes about your code:
You should never use for/in to iterate an array. for/in iterates all properties of the object which includes array elements, but can also include other enumerable properties (if any have been added to the object). Instead, use .forEach(), .map(), .reduce() or a regular for (var i = 0; i < array.length; i++) loop or in ES6, for/of.
Your sales tax calculation is not correct. You are multiplying each sub-total value which means the early values get multiplied by the sales tax value multiple times. It is simplest to just accumulate the regular total and then apply the sales tax at the end. Or, multiple the sales tax only by each new price, not by the accumulated total.
You have to decide if tip is calculated before or after taxes. This is matter of preference, but I've shown it where tip is calculated before taxes.
This statement looks incorrect
diners[d].tax2 = diners[d] * price2 * 0.082;
I guess you meant "diners[d].price2"
First off - your diners variable is not a dictionary but an array of anonymous objects. Therefore you can not index the array by objects diners[1] but only by the ordinal number of the objetc in array. For that you use for cycle.
Also you had other typos in your code.
Find fixed and working code below:
var diners=[
{name:'adam', entree1:'ramen', price1:11.5, entree2: 'miso', price2 : 3},
{name:'bobby', entree1: 'udon', price1 :10.69, entree2: 'gyoza', price2 :4.5},
{name:'carly', entree1: 'teriyaki chicken', price1:12, entree2: 'miso', price2 : 3},
];
var entrees1_total=0;
for (d=0; d < diners.length; d++){
entrees1_total += diners[d].price1; //total expense of entree1 for all diners
diners[d].tax1 = diners[d].price1 * 0.082; // method for sales tax
entrees1_total += diners[d].tax1; //total entree1 price including sales tax
}
var entrees2_total=0;
for (d=0; d < diners.length; d++){
entrees2_total += diners[d].price2;
diners[d].tax2 = diners[d].price2 * 0.082;
entrees2_total += diners[d].tax2;
}
var total = entrees1_total + entrees2_total;
var total_bill = total*1.2; //tips
console.log("total is: " + total_bill.toString());
for (var d in diners) {
console.log(diners[d].name + " spends " + (diners[d].price1 + diners[d].tax1)+(diners[d].price2 + diners[d].tax2));
} // print out total spent for each patron
You made few mistakes in second loop and you result in console.log worked like string. Not a number. So the working code is
var diners=[
{name:'adam', entree1:'ramen', price1:11.5, entree2: 'miso', price2 : 3},
{name:'bobby', entree1: 'udon', price1 :10.69, entree2: 'gyoza', price2 :4.5},
{name:'carly', entree1: 'teriyaki chicken', price1:12, entree2: 'miso', price2 : 3},
];
var entrees1_total=0;
for (var d in diners){
entrees1_total += +diners[d].price1; //total expense of entree1 for all diners
diners[d].tax1 = diners[d].price1*0.082; // method for sales tax
entrees1_total += +diners[d].tax1; //total entree1 price including sales tax
}
var entrees2_total=0;
for (var d in diners){
entrees2_total += +diners[d].price2;
diners[d].tax2 = diners[d].price2 * 0.082;
entrees2_total += +diners[d].tax2;
}
var total = entrees1_total + entrees2_total;
var total_bill = total*1.2; //tips
console.log("total is: " + total_bill.toString());
for (var d in diners) {
console.log(diners[d].name + " spends " + (diners[d].price1 +diners[d].tax1 + diners[d].price2 + diners[d].tax2));
}
:
Related
Hello so I am trying to work on this code for my Java Script class and I am stuck on how to proceed. The instructions for the problem we were given were as follows:
Create a simple self-checkout system. Prompt for the prices and quantities of three items. Calculate the subtotal of the items. Then calculate the tax using a tax rate of 5%. Print out the line items with the quantity and total, and then print out the subtotal, tax amount, and total.
Here is my code so far:
// Make a function for a simple self-checkout system.
// prompt the user for quantity of the items
// Prompt the user for the prices of the items
function self_Checkout () {
var prices = [x, y, z,];
var x = prompt('Enter value');
var quantity_x = prompt('Enter value for quantity of item 1');
return x * quantity_x;}
{ if
var y = prompt('Enter value');
var quantity_y = prompt('Enter value for quantity of item 2');
return y * quantity_y;
{ if
var z = prompt('Enter value');
var quantity_z = prompt('Enter value for quantity of item 3');
return z * quantity_y;
// Multiply entire total by a tax rate of 5%
// Return value of total of all items + tax to user
// Use console.log or document.write?
}
Now the assignment also mentions how we are supposed to use loops objects and arrays also in this problem. I have attempted to add a array in the code. Some help on how to proceed in my code would be much appreciated, hopefully i explained it well enough to get some help.
Here is working code that is all dynamic and not limited to 3 items
<!DOCTYPE html>
<html>
<head>
<script>
function getit(){
var result = document.getElementById('demo');
var allitems = 0;
var itemCount = prompt("how many items do you need?");
var items = {};
for (i = 0; i < itemCount; i++) {
items[i] = {
name : prompt("Product Name"),
price : prompt("Product Price"),
qty : prompt("Product qty")
}
}
for (i = 0; i < itemCount; i++) {
var subtotal = 0;
var total = 0;
subtotal = items[i].price * items[i].qty;
total = subtotal * 1.05;
allitems = allitems + subtotal;
result.innerHTML += "Product: " + items[i].name + "<br/>";
result.innerHTML += "Total Qty: " +items[i].qty + "<br/>";
result.innerHTML += "Sub total: " + subtotal + "<br/>";
result.innerHTML += "Sub total: " + total + "<br/>";
if(i == (itemCount - 1)){result.innerHTML += "Sub total for all items: " + allitems + "<br/>";}
}
}
</script>
</head>
<body>
<button onclick="getit()">Shop</button>
<p id="result">Creating a JavaScript Object.</p>
</body>
</html>
I'm trying to make a script for kids to practice math. I managed to make +, -, x but can't complete divisions. Project can be seen here:
http://fibeeland.com/projects/math_tasks/index.html
I'm taking random numbers from the inputs and generate tasks. How to make division calculations so only examples with no reminder are shown?
my function looks like this:
//get a random number
function randomNumber(){
var minNumberId = document.getElementById("minNrId");
var xx=minNumberId.value;
var maxNumberId = document.getElementById("maxNrId");
var yy=maxNumberId.value;
var min = Math.ceil(xx);
var max = Math.floor(yy);
var randNr1 = Math.floor(Math.random() * (max - min + 1)) + min;
return randNr1;
}
function division(min,max,tasks){
document.getElementById('division_loop').innerHTML = " ";
var tasks_quantity = document.getElementById("tasks_quantity");
var tasks = tasks_quantity.value;
for (i=0; i < tasks; i++){
var a = randomNumber();
var b = randomNumber();
if((a%b)===0){
document.getElementById('division_loop').innerHTML += "<p><span class='task_punctuation'>" + (i+1) + ". </span>" + a + " / " + b +" = <input type='text' class='answerInput' id='" + (a/b) + "'></p>";
} else{
b = 2;
document.getElementById('division_loop').innerHTML += "<p><span class='task_punctuation'>" + (i+1) + ". </span>" + a + " / " + b +" = <input type='text' class='answerInput' id='" + (a/b) + "'></p>";
}
}
$(".answerInput").keyup(function() {
var InputID = this.id;
value = $(this).val();
//change to lower case
var InputIDlow = InputID.toLowerCase();
var valuelow = value.toLowerCase();
if(valuelow==InputIDlow){
$(this).css('background-color', '#bcffb9');
}
else{
$(this).css('background-color', '#dbdbf4');
}
});
}
division();
Thank you in advance.
Matt
Okay your script seems to work if a is divisible by 2. You can check if that's the case and if not just add 1 to a.
That seems to be pretty boring for the kids :D
What about choosing a random number (just one)
For example b = 3
Then you can multiply that by a random number (you might wanna reduce the range so that the multiplication is within the bounds).
Then just say your result is a and then you just ask for a/b.
Example
b = randomNumber()
a = b*randomNumber() # adjusting the range
Then just as usually ask for a/b
**Update I have chance previous variable to return a value. I still have no solution for the loop error. When I submit it returns $5.1572...., when it should be returning around 200k. **
I have a retirement calculator that I have created for some online classes and I cannot get the loop to work. I assume that's what it is.
I have verified that the calculator is working and have no other errors but just don't seem to understand how to use the loop properly.
Any help would be appreciated.
Trying to take retire (age) - current (age) to come up with lengthOfCalulation. From there I need to take the Return (% of interest) and the PerYear ($ of investment each year) and determine the future value.
function Savings() {
var Current = Number(document.getElementById('AgeNow').value);
var Retire = Number(document.getElementById('AgeThen').value);
var Return = Number(document.getElementById('Return').value);
var PerYear = Number(document.getElementById('PerYear').value);
var lengthOfCalculation = Retire - Current;
var results;
var total = 0;
for (results=0; results < lengthOfCalculation; results++) {
total = (total + PerYear) * (1 + Return);
}
alert("When you retire your account will have $" + total.toFixed(2));
}
You are creating the variable total in each iteration and you are not using your results variable in your calculation in the loop. This loop just calculates the same result each time so it would be the same without looping at all.
Try this
function Savings() {
var Current = Number(document.myForm.AgeNow.value);
var Retire = Number(document.myForm.AgeThen.value);
var Return = Number(document.myForm.Return.value);
var PerYear = Number(document.myForm.PerYear.value);
var lengthOfCalculation = Retire - Current;
var results;
var total = 0;
for (results=0; results < lengthOfCalculation; results++) {
total += (PerYear * (1 + Return));
}
alert("When you retire your account will have $" + total.toFixed(2));
}
I am trying to loop through objects within an array, adding all values with the key 'price'.
var basket = [
{
price: "25.00",
id: "Hat"
}, {
price: "50.00",
id: "Jacket"
}
]
/*objects within array. purpose = able to use a for loop using .length as follows*/
function test() {
for(var i = 0; i < basket.length; i++){
totalPrice = 0;
alert(itemPrice);
itemNum = basket[i];
itemPrice = parseFloat(itemNum.price);
totalPrice += itemPrice;
}
alert(totalPrice);
}
My itemPrice alert shows that the loop runs through both objects, flashing 25 then 50. Why is my totalPrice variable only storing the second price, 50? The operator += should be the same as totalPrice = totalPrice + itemPrice? Any explanation as well as fixes would be very much appreciated, trying to get a good understanding!
The first time you enter the loop, you set totalPrice to 0. Then you add the first item price, so totalPrice is 25. Then you enter the loop for the second time, set totalPrice to 0 again, 0 + 50 = 50.
You should initialize totalPrice before the loop.
use reduce:
basket.reduce( function( previousValue, currentValue ){
return previousValue += parseInt(currentValue.price)
}, 0);
example: http://jsfiddle.net/ysJS8/
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce
I am writing a simple cart that to handle user input before arriving at a sum that I pass off to my payment processor. I have code that works, but I'm not sure if it's the most efficient way of calculating the total. Secondly, I would like to add the possibility for a percentage discount when three of the categories are selected. I originally had a way that did a lot of checking through IF statements, but that was inefficient and there was also an unresolved issue with it. How would I go about applying a percentage discount to my preexisting code (if three of four of the item categories are >0)?
var subtotal = 0;
var veu4 = 0;
var veo4 = 0;
var vres = 0;
var vcvl = 0;
var vedb = 0;
function update_price(pin) {
quantity = parseFloat(pin.value);
var callname = pin.name;
if (callname == "item1"){
price = quantity * 50;
subtotal -= vcvl * 50;
vcvl = quantity;
}
else if (callname == "item2"){
price = quantity * 50;
subtotal -= vres * 50;
vres = quantity;
}
else if (callname == "item3"){
price = quantity * 99;
subtotal -= veu4 * 99;
veu4 = quantity;
}
else if (callname == "item4"){
price = quantity * 129;
subtotal -= veo4 * 129;
veo4 = quantity;
}
else{
//commented out irrelevant
}
subtotal += price;
passtotal = document.getElementById("ftotal");
total = document.getElementById("ptotal");
total.innerHTML = subtotal;
passtotal.value = subtotal;
passtotal.innerHTML = subtotal;
}
}
Your help is greatly appreciated!
Many ways to do this, but this would be a bit more DRY.
var items = {
item1: 50,
item2: 50,
item3: 99,
item4: 129
};
var cart = {};
function update_price(pin) {
quantity = parseFloat(pin.value);
var callname = pin.name;
// Get the total for this item with quantity
price = quantity * items[callname];
// Update quantity in cart
cart[callname] = {quantity: quantity, subtotal: price};
passtotal = document.getElementById("ftotal");
total = document.getElementById("ptotal");
total.innerHTML = price;
passtotal.value = price;
passtotal.innerHTML = price;
}
I think your concept of totals/subtotals is weird. It seems like your total/subtotal will always be equal to your last calculation of price * quantity. Maybe your code generated is wrong. As such mine will be slightly wrong too. To fix it, make the total equal to all of the subtotals in the cart.
As for passing this data to your server, you should pass the items that will be purchased and the quantity. On the server-sider, the subtotals and totals should be recalculated. I added your cart variable to help with this. Just serialize this data and send it over to your server processing. Do not take the value of ftotal or ptotal to be accurate when you actually charge the user.