-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcart.js
71 lines (58 loc) · 1.37 KB
/
cart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
var _ = require('underscore');
//
// Adds a new item to the cart; Increments the quantity, if the item exists
//
exports.addItemToCart = function(session, itemId) {
var cart = session.cart;
if(cart) {
// Add the item to the cart - check if an cart item with the same Id exists
var found = _.find(cart, function(item){ return item.itemId == itemId });
if(found) {
// Update the items quantity
found.quantity++;
} else {
// Add as new item to cart
cart.push(createCartItem(itemId));
}
} else {
// Add new cart element to session
session.cart = [createCartItem(itemId)];
}
}
//
// Returns the list of cart items for the current sessions
//
exports.getCartItems = function(session) {
var cart = session.cart;
return cart ? cart : [];
}
//
// Helper to create a new cart item element
//
function createCartItem(itemId) {
return {
itemId: itemId,
quantity: 1
};
}
//
// Returns the current number of items in the cart
//
exports.getItemCount = function (session){
var cart = session.cart;
if(cart) {
var result = 0;
for (var i in cart) {
result += cart[i].quantity;
}
return result;
} else {
return 0;
}
}
//
// Removes all items from the cart.
//
exports.clearCart = function(session) {
delete session.cart;
}