Skip to content

Instantly share code, notes, and snippets.

@hassanuos
Forked from alexhawkins/shoppingCart.js
Created September 7, 2022 08:29
Show Gist options
  • Save hassanuos/33ba80810aa851244f35f1b50bbbc1f3 to your computer and use it in GitHub Desktop.
Save hassanuos/33ba80810aa851244f35f1b50bbbc1f3 to your computer and use it in GitHub Desktop.
Example of a Module Design Pattern in JavaScript
/*MODULE PATTERN*/
//create a namespace
var shoppingCart = (function() {
//private variables
var total;
var basket = [];
//private methods
function viewCart() {
basket.forEach(function(el) {
console.log(el.item + '\t\t$' + el.price);
})
};
//public variables and methods
return {
//public alias to private function
getCart: viewCart,
addItem: function(values) {
basket.push(values);
return this;
},
removeItem: function(name) {
basket.forEach(function(product, index) {
if (name === product.item) {
basket.splice(index, 1);
}
});
return this;
},
getItemCount: function() {
return basket.length;
},
getTotal: function() {
total = 0;
basket.forEach(function(item) {
total += item.price;
})
return total;
}
}
}());
shoppingCart.addItem({
item: 'Bobby Socks',
price: 1.99
}).addItem({
item: 'Pink T-shirt',
price: 10.99
}).addItem({
item: 'AquaFresh',
price: 43.98
}).addItem({
item: 'Visine Ultra',
price: 4.99
}).addItem({
item: 'Bobby Socks',
price: 1.99
});
shoppingCart.getCart();
/*
Bobby Socks $1.99
Pink T-shirt $10.99
AquaFresh $43.98
Visine Ultra $4.99
Bobby Socks $1.99
*/
console.log((shoppingCart.getTotal()).toFixed(2)); //63.94
shoppingCart.removeItem('Visine Ultra'); //63.94
console.log((shoppingCart.getTotal()).toFixed(2)); //58.95
console.log(shoppingCart.removeItem('Bobby Socks').getTotal()); //54.97
console.log(shoppingCart.getItemCount()); // 2
shoppingCart.getCart();
/*
Pink T-shirt $10.99
AquaFresh $43.98
*/
console.log((shoppingCart.getTotal()).toFixed(2)); //54.97
shoppingCart.addItem({
item: 'Samsung Galaxy',
price: 499.99
}).addItem({
item: 'Apple Ipad',
price: 750.99
}).addItem({
item: 'Eloquent JS',
price: 24.98
}).addItem({
item: 'Trojan Condoms',
price: 8.99
}).addItem({
item: 'Tube Sock',
price: 1.99
});
shoppingCart.getCart();
/*
Pink T-shirt $10.99
AquaFresh $43.98
Samsung Galaxy $499.99
Apple Ipad $750.99
Eloquent JS $24.98
Trojan Condoms $8.99
Tube Sock $1.99
*/
console.log((shoppingCart.getTotal()).toFixed(2)); //1341.91
shoppingCart.removeItem('Samsung Galaxy');
shoppingCart.getCart();
/*
Pink T-shirt $10.99
AquaFresh $43.98
Apple Ipad $750.99
Eloquent JS $24.98
Trojan Condoms $8.99
Tube Sock $1.99
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment