Building a Cash Register - 7 You Deserved It! (Using prompt)


#1

Well, guys I'd like to do a more interactive using prompt box.
But I take this output:
"Your bill is NaN"
using:
cashRegister.applyStaffDiscount(prompt("Type me, sally or bob bellow and OK", "type your choice here"));

with
cashRegister.applyStaffDiscount(me);

output:
"Your bill is 13.74"

=====> Is there a way of using prompt, or how can I fix this issue?

function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}

var sally = new StaffMember("Sally",5);
var bob = new StaffMember("Bob",10);

// Create yourself again as 'me' with a staff discount of 20%
var me = new StaffMember("Marcel", 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;
},
// Create a new method applyStaffDiscount here
applyStaffDiscount: function(employee){
this.total -= this.total * (employee.discountPercent / 100);
}

};

cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',3);
// Apply your staff discount by passing the 'me' object
// to applyStaffDiscount

//cashRegister.applyStaffDiscount(me);

cashRegister.applyStaffDiscount(prompt("Type me, sally or bob bellow and OK", "type your choice here"));

// Show the total bill
console.log('Your bill is '+cashRegister.total.toFixed(2));


#2

Problem is that prompt returns a string. So if I type sally I get "sally". What you want to do is to get a variable by its name. You can do that by referencing to the parent variable. In the case of global variables, it is a window object.

cashRegister.applyStaffDiscount(window[prompt("Type me, sally or bob bellow and OK", "type your choice here")]);

#4

This is exactly the same code as @marcelvip has posted.

prompt returns a string. It is usually a good idea to test your idea before posting.


#5

yea, my bad I was testing it on my code and it's different now that I look, I will delete that post


#6

thank you for your help


#7

Thank you so much!

Now it runs!


#8

Leave it here to other people


#9

You're very welcome.