Created
July 9, 2014 05:55
-
-
Save prakhar1989/ab6761737c17906d5584 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| angular.module("xciteServices", []) | |
| .factory('CartService', function() { | |
| // Factory for Cart Items | |
| var cartItems = angular.copy(window.Globals.CartItems); | |
| return { | |
| // private function to find item with itemId | |
| _findItem: function(itemId) { | |
| var index = -1; | |
| for (var i in cartItems) { | |
| if (cartItems[i].id === itemId) { | |
| index = i; | |
| } | |
| } | |
| return index; | |
| }, | |
| // private function to find total of cart items | |
| _getTotal: function() { | |
| var total = 0.0; | |
| for (var i in cartItems) { | |
| total += parseFloat(cartItems[i].value); | |
| } | |
| return total; | |
| }, | |
| getItems: function() { | |
| return cartItems; | |
| }, | |
| // removes an item on cart with the matching id | |
| removeItem: function(itemId) { | |
| var index = this._findItem(itemId); | |
| if (index > -1) { | |
| cartItems.splice(index, 1); | |
| } | |
| }, | |
| // adds an item of schema id, value and label to cart | |
| addItem: function(item) { | |
| var index = this._findItem(item.id); | |
| var total = this._getTotal(); | |
| var value_to_add = item.value; | |
| /* if the item is a discount and if discount > cart total | |
| * set value correctly so that cart doesn't get negative | |
| */ | |
| if (item.value < 0) { | |
| if (total < Math.abs(item.value)) { | |
| value_to_add = -1 * total; | |
| } | |
| if (total === 0) { | |
| value_to_add = 0; | |
| } | |
| } | |
| // if item already added, dont change else add | |
| if (index === -1) { | |
| cartItems.push({ id: item.id, label: item.label, value: value_to_add }); | |
| } | |
| } | |
| } | |
| }) |
Author
prakhar1989
commented
Jul 9, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment