Skip to content

Instantly share code, notes, and snippets.

@prakhar1989
Created July 9, 2014 05:55
Show Gist options
  • Select an option

  • Save prakhar1989/ab6761737c17906d5584 to your computer and use it in GitHub Desktop.

Select an option

Save prakhar1989/ab6761737c17906d5584 to your computer and use it in GitHub Desktop.
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 });
}
}
}
})
@prakhar1989
Copy link
Author

describe('services', function() {
    beforeEach(module('xciteServices'));

    describe("cart service", function() {
        var CartService;
        var window = {Globals: {CartItems: {}}};

        beforeEach(inject(function (_CartService_) {
            CartService = _CartService_;
        }));

        it("should return blank total correctly", function() {
            expect(CartService._getTotal()).toBe("0");
        });

    });

});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment