Javascript Bytes (4): A Vending Machine

//function for vending machine
var vendingMachine = (function() {
//make items inside the vending machine
//return this.label is telling js to return only the label property of the object instead
//of the entire thing
var items = [
{ id: ‘001’, label: “Snickers”, price: 1.00, toString: function() {return this.label } },
{ id: ‘002’, label: “M&Ms”, price: 1.50, toString: function() {return this.label } },
{ id: ‘003’, label: “Amstel Light”, price: 3.00, function() {return this.label} }

];

//return the float to a fixed decimal point
var toMoney = function(value) {
return ‘$’ + value.toFixed(2);

}

//a function to vend the item
var vend = function(money, id) {
//verify money is greater than or equal to the price of the cheapest item
//verify the item exists
var item = findItem(id);
var msg, item_or_refund;
//check docu for toFixed()
//function orientated programming
if (toMoney(money) >= toMoney(item.price)) {
msg = ‘Vended ‘ + item.label + ‘ for ‘ + toMoney(item.price).toString() + ‘.’;
item_or_refund = item;

} else {
msg = “Sorry, not enough funds!”;
item_or_refund = toMoney(money).toString();
}

console.log(msg);
return item_or_refund;
};

//takes an id and return the result of an item’s filter – go over each item, does your id match the one we want? toss it till we find a match

//function to find the right item
var findItem = function(id){
return items.filter(function(item) {
console.log(item.id);
return id.toString() === item.id.toString();

})[0];

}

//shows all the items
var menu = function() {
items.forEach(function(item) {
console.log(item.id + “: ” + item.label);

});
};

//exits main function, vends the item
//must return all the subfunctions
return {
vend: vend,
menu: menu,
toMoney: toMoney
};
})();

console.log(vendingMachine.vend(1.00,’002′));

console.log(vendingMachine.vend(3.00,’003′));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s