Advertisement
hjerting

Online Shopping Lab

Sep 21st, 2016
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. var cart = [];
  2.  
  3. function setCart(newCart) {
  4. cart = newCart;
  5. }
  6.  
  7. function total() {
  8. let t = 0
  9.  
  10. for (var i = 0, l = cart.length; i < l; i++) {
  11. t += cart[i]['price'];
  12. }
  13.  
  14. return t
  15. }
  16.  
  17. function getCart() {
  18. return cart;
  19. }
  20.  
  21. function addToCart(item) {
  22. var price = Math.floor(Math.random() * 100) + 1;
  23. cart.push({ item : item, price : price });
  24. console.log(`${item} has been added to your cart.`);
  25. return cart;
  26. }
  27.  
  28. function viewCart() {
  29. var cartItems = cart.length;
  30. if (cartItems === 0) {
  31. console.log('Your shopping cart is empty.');
  32. }
  33. var cartString = 'In your cart, you have ';
  34. for (var i = 0; i < cartItems; i++) {
  35. cartString += `${cart[i]['item']} at ${cart[i]['price']}`;
  36. if (i + 1 < cartItems) {
  37. cartString += ', ';
  38. }
  39. }
  40. cartString += '.';
  41. console.log(cartString);
  42. return cartString;
  43. }
  44.  
  45. function removeFromCart(item) {
  46. var removed = false;
  47. for (x in cart) {
  48. if (cart[x]['item'] === item) {
  49. cart.splice(x, 1);
  50. removed = true;
  51. }
  52. }
  53. if (removed) {
  54. return cart;
  55. }
  56. else {
  57. console.log("That item is not in your cart.");
  58. return false;
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement