<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
//Definition of staff members (class)
function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}
//Creation of staff members (object)
var s121 = new StaffMember("Sally",5);
var b122 = new StaffMember("Bob",10);
var d123 = new StaffMember("Dave",20);
staffMembers = [s121,b122,d123];
//Creation of cash register (object)
var cashRegister = {
total:0,
lastTransactionAmount: 0,
//Add to the total (method)
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
//Retreive the value of an item (method)
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
//Void the last item (method)
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
//Apply a staff discount to the total (method)
applyStaffDiscount: function(employee) {
this.total -= this.total * (employee.discountPercent / 100);
}
};
//Ask for number of items
do {
var numOfItems = prompt("How many items do you have?");
document.body.innerHTML = numOfItems;
if (isNaN(numOfItems)) {
i=0;
} else {
i=1;
}
} while (i===0);
//Ask for item and qty of item
var items = [];
var qtys = [];
for(var i=0;i<numOfItems;i++) {
var j=0;
do {
items[i] = prompt("What are you buying? (eggs, milk, magazine, chocolate)");
switch (items[i]) {
case "eggs" :;
case "milk" :;
case "magazine" :;
case "chocolate" : j=1; document.body.innerHTML = items[i]; break;
default : document.body.innerHTML = 'Item not reconized, please re-enter...'
; break;}
} while (j===0);
do {
qtys[i] = prompt("How many " + items[i] + " are you buying?");
document.body.innerHTML = qtys[i];
if (isNaN(qtys[i])) {
j=1;
} else {
j=0;
}
} while (j===1);
//Add to the sub-total
cashRegister.scan(items[i],qtys[i])
}
//Find out if it's a staff member & if so apply a discount
var customer;
var staffNo;
do {
customer = prompt("Please enter customer name or type 'staff'.");
document.body.innerHTML = customer;
if (customer === 'staff') {
staffNo = prompt("Please enter your staff number");
for (i in staffMembers) {
if (staffMembers[i] === staffNo) {
cashRegister.applyStaffDiscount(staffNo);
} else {
document.body.innerHTML = "Staff number not found";
};
}
}
i=1;
} while (i=0);
// Show the total bill
if (customer !== 'staff') {
document.body.innerHTML = 'Your bill is £'+cashRegister.total.toFixed(2)
+' Thank you for visiting ' +customer;
} else {
document.body.innerHTML = 'Your bill is £'+cashRegister.total.toFixed(2)
+' Thank you for visiting ' +staffNo;
};
</script>
</body>
</html>
What seems to be wrong with my code, it works but does not apply the staff discount, I feel the error is around;
for (i in staffMembers) {
if (staffMembers[i] === staffNo) {
cashRegister.applyStaffDiscount(staffNo);
} else {
document.body.innerHTML = "Staff number not found";
};
}
Can anybody help spot the error, I've been learning on CodeAcademy but have taken the final example further with checks on data entered. But I can't seem to see why this section is not working as it should when checked via 'http://www.compileonline.com/try_javascript_online.php'.
It turns out there is quite a lot wrong with your code. The key things you need to fix to get it "working" are the following:
First - you are asking for a "staff number", but your employee structure doesn't have space for that. You could modify the StaffMember as follows:
//Definition of staff members (class)
function StaffMember(name, number, discountPercent){
this.name = name;
this.number = number;
this.discountPercent = discountPercent;
}
//Creation of staff members (object)
var s121 = new StaffMember("Sally","s121",5);
var b122 = new StaffMember("Bob","b122",10);
var d123 = new StaffMember("Dave","d123",20);
staffMembers = [s121,b122,d123];
Now you have a "unique identifier" - I decided to give the employee the same number as the variable name, but that is not necessary.
Next, let's look at the loop you had: change it to
do {
customer = prompt("Please enter customer name or type 'staff'.");
document.body.innerHTML = customer;
if (customer === 'staff') {
staffNo = prompt("Please enter your staff number:");
for (i in staffMembers) {
if (staffMembers[i].number === staffNo) { // <<<<< change the comparison
cashRegister.applyStaffDiscount(staffMembers[i]); // <<<<< call applyStaffDiscount with the right parameter: the object, not the staff number
} else {
document.body.innerHTML = "Staff number not found";
};
}
}
i=1; // <<<<< I really don't understand why you have this do loop at all.
} while (i == 0); // <<<<< presumably you meant "while(i == 0)"? You had "while (i=0)"
There are many, many things you could do to make this better - but at least this will get you started. Complete "working" code (I may have made other edits that I forgot to point out - but the below is copied straight from my working space, and "works" - albeit rather flaky):
<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
//Definition of staff members (class)
function StaffMember(name, number, discountPercent){
this.name = name;
this.number = number;
this.discountPercent = discountPercent;
}
//Creation of staff members (object)
var s121 = new StaffMember("Sally","s121",5);
var b122 = new StaffMember("Bob","b122",10);
var d123 = new StaffMember("Dave","d123",20);
staffMembers = [s121,b122,d123];
//Creation of cash register (object)
var cashRegister = {
total:0,
lastTransactionAmount: 0,
//Add to the total (method)
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
//Retreive the value of an item (method)
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
//Void the last item (method)
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
//Apply a staff discount to the total (method)
applyStaffDiscount: function(employee) {
this.total -= this.total * (employee.discountPercent / 100);
}
};
//Ask for number of items
do {
var numOfItems = prompt("How many items do you have?");
document.body.innerHTML = numOfItems;
if (isNaN(numOfItems)) {
i=0;
} else {
i=1;
}
} while (i===0);
//Ask for item and qty of item
var items = [];
var qtys = [];
for(var i=0;i<numOfItems;i++) {
var j=0;
do {
items[i] = prompt("What are you buying? (eggs, milk, magazine, chocolate)");
switch (items[i]) {
case "eggs" :;
case "milk" :;
case "magazine" :;
case "chocolate" : j=1; document.body.innerHTML = items[i]; break;
default : document.body.innerHTML = 'Item not reconized, please re-enter...'
; break;}
} while (j===0);
do {
qtys[i] = prompt("How many " + items[i] + " are you buying?");
document.body.innerHTML = qtys[i];
if (isNaN(qtys[i])) {
j=1;
} else {
j=0;
}
} while (j===1);
//Add to the sub-total
cashRegister.scan(items[i],qtys[i])
}
//Find out if it's a staff member & if so apply a discount
var customer;
var staffNo;
do {
customer = prompt("Please enter customer name or type 'staff'.");
document.body.innerHTML = customer;
if (customer === 'staff') {
staffNo = prompt("Please enter your number:");
for (i in staffMembers) {
if (staffMembers[i].number === staffNo) {
cashRegister.applyStaffDiscount(staffMembers[i]);
} else {
document.body.innerHTML = "Staff number not found";
};
}
}
i=1;
} while (i=0);
// Show the total bill
if (customer !== 'staff') {
document.body.innerHTML = 'Your bill is £'+cashRegister.total.toFixed(2)
+'<br> Thank you for visiting ' + customer;
} else {
document.body.innerHTML = 'Your bill is £'+cashRegister.total.toFixed(2)
+'<br> Thank you for visiting staff member ' +staffNo;
};
</script>
</body>
</html>
In every singe loop there is an element from stattMembers in i, not its position. So you don't get 0, 1, 2 in it but staffMembers[0], staffMembers[1], staffMembers[2]. You should think about this, maybe a simple for-loop is better in your case?
The problem lies in these lines
if (staffMembers[i] === staffNo) {
cashRegister.applyStaffDiscount(staffNo);
}
it should have been
if (i === staffNo) {
cashRegister.applyStaffDiscount(staffMembers[i]);
}
Since you are first validating for the existence of the index(no) of a staff, then i == staffNo should be the right condition.
cashRegister.applyStaffDiscount() expects an instance of a StaffMember so passing on to the staffMembers[i] object does the trick.
Related
I've created a simple higher or lower card guessing game, it works but once it completes once it then loops through the game logic n^2 times and I cant explain why. I'm really new to coding and JavaScript and I cant figure out what's happening. The issue I currently have is while I'm able to look up concepts in isolation I don't understand enough about the bigger picture to know what interaction is causing the looping.
less useful further info:
Currently the whole script is really a proof of concept, ultimately I will replace the deck building function and just use the random number generator to find images of cards, record all of the previous game events and remove cards from the deck as the game progresses but I cant have it looping by the square of the number of times its been through the game cycle.
Here is the code, please feel free to talk to me like I'm 5, I currently feel like a monkey with a gun.
console.log(">>>>>>>>>>>>>>>>>>>>>>> SCRIPT START");
console.log("variables are defined");
var suitClubs = [];
var suitDiamonds = [];
var suitHearts = [];
var suitSpade = [];
var history = [];
var userGuess;
var activeCard;
var nextCard;
var randomSuitOne;
var randomCardOne;
var randomSuitTwo;
var randomCardTwo;
var activeCardValue;
var nextCardValue;
var gameCycle = 0;
const card = document.querySelector(".card");
const title = document.querySelector(".title");
const historyP = document.querySelector(".history-p");
console.log("buildDeck() is called")
buildDeck();
function buildDeck() {
console.log("Deck is built");
for (i = 1; i <= 13; i++) {
suitDiamonds.push(i + " Diamond");
}
for (i = 1; i <= 13; i++) {
suitHearts.push(i + " Heart");
}
for (i = 1; i <= 13; i++) {
suitClubs.push(i + " Club");
}
for (i = 1; i <= 13; i++) {
suitSpade.push(i + " Spade");
}
var deck = suitClubs.concat(suitDiamonds, suitHearts, suitSpade);
console.log("cardChoice is called");
cardChoice();
};
function cardChoice() {
gameCycle = gameCycle + 1;
console.log(">>>>>>>>>>>>>>>>>>>>>>> GAME CYCLE START");
title.innerHTML = "Higher or Lower!"
activeSequenceCard();
// console.log("activeSequenceCard is called to randomize the active card");
function activeSequenceCard() {
randomSuitOne = Math.floor((Math.random() * 4) + 1);
randomCardOne = Math.floor((Math.random() * 13));
switch (randomSuitOne) {
case 1:
activeCard = suitClubs[randomCardOne];
break;
case 2:
activeCard = suitDiamonds[randomCardOne];
break;
case 3:
activeCard = suitSpade[randomCardOne];
break;
case 4:
activeCard = suitHearts[randomCardOne];
break;
}
card.innerHTML = activeCard;
nextSequenceCard();
// console.group("nextSequenceCard is called to randomize the next card in the deck")
}
function nextSequenceCard() {
randomSuitTwo = Math.floor((Math.random() * 4) + 1);
randomCardTwo = Math.floor((Math.random() * 13));
switch (randomSuitTwo) {
case 1:
nextCard = suitClubs[randomCardTwo];
break;
case 2:
nextCard = suitDiamonds[randomCardTwo];
break;
case 3:
nextCard = suitSpade[randomCardTwo];
break;
case 4:
nextCard = suitHearts[randomCardTwo];
break;
}
historyP.innerHTML = ("The next card will be: " + nextCard);
console.log("randomSuitOne is: " + randomSuitOne + " randomCardOne is: " + randomCardOne);
console.log("randomSuitTwo is: " + randomSuitTwo + " randomCardTwo is: " + randomCardTwo);
gamePlay();
}
}
function gamePlay() {
for (let i = 0; i < 2; i++) {
document.getElementsByClassName("game-button")[i].addEventListener("click", function () {
userGuess = parseInt(this.value);
console.log("The users guess was button (" + this.value + ") " + this.innerHTML + " and is a: " + typeof this.value);
switch (userGuess) {
case 1: console.log("User clicked HIGHER");
if (activeCardValue <= nextCardValue) {
console.log("Case 1: TRUE fired");
title.innerHTML = "CORRECT!"
setTimeout(cardChoice, 2000);
break;
} else {
console.log("Case 1: FALSE fired");
title.innerHTML = "GAME OVER!"
}
break;
case 2: console.log("User clicked LOWER");
if (activeCardValue >= nextCardValue) {
console.log("Case 2: TRUE fired");
title.innerHTML = "CORRECT!"
setTimeout(cardChoice, 2000);
break;
} else {
console.log("Case 2: FALSE fired");
title.innerHTML = "GAME OVER!"
}
break;
} console.log(">>>>>>>>>>>>>>>>>>>>>>> GAME CYCLE ENDS, this is cycle: " + gameCycle);
})
}
activeCardValue = activeCard.split(" ");
activeCardValue = parseInt(activeCardValue.splice(0, 1));
console.log("activeCardValue is: " + activeCardValue);
nextCardValue = nextCard.split(" ");
nextCardValue = parseInt(nextCardValue.splice(0, 1));
console.log("nextCardValue is: " + nextCardValue);
}
At this current moment I've been trying to work through an issue I've had with my Hangman JS game. I've spent the last week attempting to replace "underscores", which I have as placeholders for the current secret word. My idea was to loop through the correctLettersOUT, and wherever that particular letter exists in the placeholder would replace it with said letter. This small part of my code below is where the issue is I believe, but I have also created a function in my whole code if a new function necessary.
Any advice is appreciated.
function startGame() {
var testWord = document.getElementById("randTest").innerHTML = secretWord;
var correctLettersOUT = "";
document.getElementById("currentGuess").innerHTML = secretBlanks(secretWord)
function secretBlanks(secretWord) {
for (var i = 0; i < secretWord.length; i++) {
correctLettersOUT += ("_ ");
}
return correctLettersOUT;
}
}
The snippet of my JS is below, it may be large but all of it is necessary. If you wish to view the whole code in it's entirety, the link is CodePen Link.
var guessWords = ["school", "test", "quiz", "pencil", "ruler", "protractor", "teacher", "homework", "science", "math", "english", "history", "language", "elective", "bully", "grades", "recess", ];
var secretWord = guessWords[Math.floor(Math.random() * guessWords.length)];
var wrongLetters = [];
var correctLetters = [];
var repeatLetters = [];
var guesses = Math.round((secretWord.length) + (.5 * secretWord.length));
var correctLettersOUT = "";
function startGame() {
var testWord = document.getElementById("randTest").innerHTML = secretWord;
var correctLettersOUT = "";
document.getElementById("currentGuess").innerHTML = secretBlanks(secretWord)
function secretBlanks(secretWord) {
for (var i = 0; i < secretWord.length; i++) {
correctLettersOUT += ("_ ");
}
return correctLettersOUT;
}
}
function correctWord() {
var guessLetter = document.getElementById("guessLetter").value;
document.getElementById("letter").innerHTML = guessLetter;
for (var i = 0; i < secretWord.length; i++) {
if (correctLetters.indexOf(guessLetter) === -1)
{
if (guessLetter === secretWord[i]) {
console.log(guessLetter === secretWord[i]);
correctLettersOUT[i] = guessLetter;
correctLetters.push(guessLetter);
break;
}}
}
if (wrongLetters.indexOf(guessLetter) === -1 && correctLetters.indexOf(guessLetter) === -1) {
wrongLetters.push(guessLetter);
}
console.log(correctLetters); //Used to see if the letters were added to the correct array**
console.log(wrongLetters);
wordGuess();
}
function wordGuess() {
if (guessLetter.value === '') {
alert("You didn't guess anything.");
} else if (guesses > 1) {
// Counts down.
guesses--;
console.log('Guesses Left: ' + guesses);
// Resets the input to a blank value.
let guessLetter = document.getElementById('guessLetter');
guessLetter.value = '';
} else {
console.log('Game Over');
}
//console.log(guesses)
}
function replWord() { }
One solution to see if the word has been guessed completely and create the partially guessed display with the same info, is to keep a Set with the not yet guessed letters, initialized at game start unGuessed = new Set(secretWord);
Since the Set's delete method returns true if the letter was actually removed (and thus existed), it can be used as a check if a correct letter was entered.
Subsequently, the display can be altered in a single place (on startup and after guessing), by mapping the letters of the word and checking if the letter is already guessed:
function alterDisplay(){
document.getElementById("currentGuess").innerHTML =
[...secretWord].map(c=>unGuessed.has(c) ? '_' : c).join(' ');
}
Some mockup code:
let guessWords = ["school", "test", "quiz", "pencil", "ruler", "protractor", "teacher", "homework", "science", "math", "english", "history", "language", "elective", "bully", "grades", "recess", ],
secretWord, unGuessed, guesses;
function startGame() {
secretWord = guessWords[Math.floor(Math.random() * guessWords.length)];
guesses = Math.round(1.5 * secretWord.length);
unGuessed = new Set(secretWord);
setStatus('');
alterDisplay();
}
function alterDisplay(){
document.getElementById("currentGuess").innerHTML = [...secretWord].map(c=>unGuessed.has(c) ? '_' : c).join(' ');
}
function setStatus(txt){
document.getElementById("status").innerHTML = txt;
}
function correctWord() {
let c= guessLetter.value[0];
guessLetter.value = '';
if (!c) {
setStatus("You didn't guess anything.");
}
else if(unGuessed.delete(c)){
alterDisplay();
if(!unGuessed.size) //if there are no unguessed letters left: the word is complete
setStatus('Yep, you guessed it');
}
else if(--guesses < 1){
setStatus('Game Over!');
}
else
setStatus('Guesses Left: ' + guesses);
}
startGame();
let gl = document.getElementById("guessLetter");
gl.onkeyup= correctWord; //for testing: bind to keyup
gl.value = secretWord[1];correctWord(); //for testing: try the 2nd letter on startup
<div id=currentGuess></div>
<input id=guessLetter><span id=letter></span>
<div id='status'></div>
Hi im writing a funciton in JavaScript
Question: Define a function viewCart which does not accept any arguments. This function should loop over every item in cart to print out "In your cart you have [item and price pairs].". If there isn't anything in your cart, the function should print out "Your shopping cart is empty.".
here is what I have
var cart = [];
function setCart(newCart) {
cart = newCart;
}
function getCart() {
return cart;
}
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
cart.push({
item: price
});
console.log(item + " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
var ItemPriceObj = cart[i];
var item = Object.keys(ItemPriceObj);
var price = ItemPriceObj['item'];
newArray.push(` ${item} at \$${price}`)
}
console.log(`In your cart, you have ${newArray}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}
My output:
'In your cart, you have socks at $undefined, puppy at $undefined, iPhone at $undefined.'
Wanted Output:
'In your cart, you have socks at $3, puppy at $23, iPhone at $400.'
From Tibrogargan's comment:
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
var ItemPriceObj = cart[i];
var item = Object.keys(ItemPriceObj);
var price = ItemPriceObj['item'];
newArray.push("" + item + " at $" + price)
}
console.log("In your cart, you have " + newArray.join(","));
} else {
return console.log('Your shopping cart is empty.');
}
}
Using "interpolated strings" isn't valid in Javascript, instead you must concatenate them
Here is something you could do. Updated the item Name and price retrieval.
var cart = [];
function setCart(newCart) {
cart = newCart;
}
function getCart() {
return cart;
}
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
var obj = {};
obj[item] = price;
cart.push(obj);
console.log(item + " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
var itemPriceObj = cart[i];
var itemKeys = Object.keys(itemPriceObj);
var item = itemKeys.filter(function(key) {
return itemPriceObj.hasOwnProperty(key)
});
var price = itemPriceObj[item];
newArray.push(`${item} at $${price}`);
}
console.log(`In your cart, you have ${newArray}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}
addToCart("Sock");
addToCart("Phone");
addToCart("Tab");
addToCart("Book");
addToCart("Keyboard");
viewCart();
You're indexing your cart item using the string "item", not the actual item name. Very easy fix:
Change this line:
var price = ItemPriceObj['item'];
To this:
var price = ItemPriceObj[item];
Maybe want to consider changing your cart element property names (mainly for readability), but also to make some things a little easier to do, for instance:
function addToCart(newItem) {
var price = Math.floor(Math.random() * 10);
cart.push({
item: newItem, price: price
});
console.log(newItem+ " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
newArray.push(` ${cart[i].item} at \$${cart[i].price}`)
}
console.log(`In your cart, you have ${newArray}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}
Alternative for viewCart (some may argue at a cost to readability) - but this would be even more verbose if the property names were variable
function viewCart() {
if (cart.length != 0) {
console.log(cart.reduce( (p,e,i) => `${p}${i?',':''} ${e.item} at \$${e.price}`, "In your cart, you have" ));
} else {
return console.log('Your shopping cart is empty.');
}
}
Using language features to make the code more "simple":
var cart = [];
function Item(item, price) {
this.item = item;
this.price = price;
}
Item.prototype.toString = function() {
return `${this.item} at \$${this.price}`
}
function addToCart(item, price) {
if (!(item instanceof Item)) {
if (typeof price === "undefined") {
price = Math.floor(Math.random() * 10);
}
item = new Item(item, price);
}
cart.push( item );
console.log(item + " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
console.log(`In your cart, you have ${cart.join(", ")}`);
} else {
return console.log('Your shopping cart is empty.');
}
}
addToCart("socks", 3.00);
addToCart("puppy", 23.00);
addToCart("iPhone", 400.0);
document.addEventListener( "DOMContentLoaded", viewCart, false );
You aren't using the object literal notation correctly. You probably want something like this.
Change addToCart() to this:
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
cart.push({
item: item,
price: price
});
console.log(item + " has been added to your cart.");
return cart;
}
And change viewCart() to this:
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
newArray.push(` ${cart[i].item} at \$${cart[i].price}`)
}
var itemPriceList = newArray.join(', '); // This will concatenate all the strings in newArray and add commas in between them
console.log(`In your cart, you have ${itemPriceList}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}
This is a function for a simple shopping app (kinda) thing that I coded to work on my JS skills, considering my elementary experience in it. But everything works except for one thing:
The applyStaffDiscount function doesn't seem to work. Everytime I try to apply an employee discount, the program just returns the same original value that was present before trying to apply the discount. Please help and also let me know how I can improve this program.
function StaffMember(name, discountPercent) {
this.name = name;
this.discountPercent = discountPercent;
}
var sally = new StaffMember("sally", 5);
var bob = new StaffMember("bob", 10);
var arhum = new StaffMember("arhum", 20);
var cashRegister = {
total: 0,
lastTransactionAmount: 0,
add: function(itemCost) {
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item, quantity) {
switch (item) {
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction: function() {
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
applyStaffDiscount: function(employee) {
this.total -= (this.total * (employee.discountPercent/100))
}
};
var cont = confirm("Are you ready to shop?")
while (cont) {
var user = ("Choose your function: A to Add Item, ED for Employee Discount, VT to Void Transaction or just X to Close")
var askUser = prompt(user).toUpperCase()
if (askUser === "A") {
var itemName = prompt("What item would you like?", "Eggs, Milk, Magazine, Chocolate").toLowerCase()
var itemNum = prompt("How many?")
cashRegister.scan(itemName, itemNum)
var cont = confirm("Your total bill is $" + cashRegister.total.toFixed(2) + ". Would you like anything else?")
}
else if (askUser === "ED") {
var name1 = prompt("Please enter you name").toLowerCase()
cashRegister.applyStaffDiscount[name1]
alert("Your total bill is $" + cashRegister.total.toFixed(2) + ".")
}
else if (askUser === "VT") {
cashRegister.voidLastTransaction()
alert("Your previous transaction has been voided. Your total bill is $" + cashRegister.total.toFixed(2) + " now.")
}
else if (askUser === "X") {
cont = false
}
if (cont === false) {
alert("We hope you had a good time. have a nice day!")
}
}
calling applyStaffDiscount should be done as shown below
cashRegister.applyStaffDiscount(name1);
Then inside applyStaffDiscount function, it should be accessed as below
this.total -= (this.total * (window[employee].discountPercent/100))
You didn't call the function in here:
cashRegister.applyStaffDiscount[name1]
Try it with something like this:
cashRegister.applyStaffDiscount(name1);
My code seems to log the if statement as false, even though if I console.log the conditions it returns as true. Why is it doing that? (the code , that is not working is indicated by error not bypassing.)
function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}
function Stock(item){
this.item = item;
}
//Global Variables
var staffMembers = {};
var sally = new StaffMember("Sally",0.05);
staffMembers['sally'] = sally;
var bob = new StaffMember("Bob",0.10);
staffMembers['bob'] = bob;
var me = new StaffMember("Aaron",0.20);
staffMembers['me'] = me;
//item variables
var eggs = new Stock("Eggs");
var milk = new Stock("Milk");
var magazine = new Stock("Magazine");
var chocolate = new Stock("Chocolate");
//item Objects
var Stock = {};
Stock['eggs'] = eggs;
Stock['milk'] = milk;
Stock['magazine'] = magazine;
Stock ['chocolate'] = chocolate;**
var cashRegister = {
total:0,
lastTransactionAmount: 0,
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
// Create a new method applyStaffDiscount here
applyStaffDiscount : function(employee){
this.total -= this.total*(employee.discountPercent);
}
};
$(document).ready(function(){
$('#target2').hide();
$('#check').on('click', function(e){
e.preventDefault();
var item = $('#item').val();
var quantity = $('#quantity').val();
var staff = $('#staff').val();
cashRegister.scan(item, quantity);
//ERROR IN CODE NOT BYPASSING
if(item === Stock['item'] && quantity > 0) {
cashRegister.scan(item, quantity);
}
///
else {
alert("This Item Does Not Exist!");
}
if(staff.length > 0 && typeof staffMembers[staff] !='undefined'){
cashRegister.applyStaffDiscount(staffMembers[staff]);
}
var output = document.getElementById("result");
result.innerHTML = 'Your bill is ' + cashRegister.total.toFixed(2);
$('#target2').fadeIn(5000)
// .animate({opacity: 0.5}, 3000)
.fadeOut(5000);
});
$('#target').submit(function(){
var info = $(this).serializeJSON();
console.log(info);
var data = JSON.parse('[info]');
console.log(data);
return false;
});
});
Stock['item'] is going to return undefined because Stock['item'] is not declared. You declare Stock['milk'], Stock['magazine'],Stock['eggs'], and Stock['chocolate'], but not Stock['item']. If you were trying to use it as a variable, you should remove the quotes.
You are also overwriting your "Stock" function with a "Stock" object, which is not causing trouble right now but it could cause issues later down the line. You should rename those to be different if possible.
Try using Stock[item] !== undefined && quantity > 0 in place of your current if expression
You did not post your HTML or a working fiddle, but my guess is your if statement should be:
if(item === Stock[item] && quantity > 0) {
cashRegister.scan(item, quantity);
}
Stock['item'] returns undefined as you're not calling it either with an object context like obj.Stock() or after using bind or call, so this is undefined. It's not returning anything either, so no assignment is made. I'm assuming $('#item').val() also. $('#item') is most likely null, triggering a runtime error and stopping your if sentence.