Skip to content

Commit

Permalink
Refactor add/remove
Browse files Browse the repository at this point in the history
  • Loading branch information
jsor committed Mar 2, 2015
1 parent 6760209 commit 9fa4571
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 18 deletions.
40 changes: 24 additions & 16 deletions carty.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,13 @@ function createCart(options) {
};

cart.add = function(item) {
if (emit('add', item)) {
emit('added', add(item));
}
add(item);

return cart;
};

cart.remove = function(item) {
if (emit('remove', item)) {
emit('removed', remove(item));
}
remove(item);

return cart;
};
Expand Down Expand Up @@ -260,35 +256,47 @@ function createCart(options) {
}

function add(attr) {
var item = createItem(attr),
existing = has(item)
;
var item = createItem(attr);

if (!emit('add', item)) {
return;
}

var existing = has(item);

if (existing) {
var newAttr = extend({}, existing.item(), item(), {
item = createItem(extend({}, existing.item(), item(), {
quantity: existing.item.quantity() + item.quantity()
});
}));
}

if (item.quantity() <= 0) {
remove(item);
return;
}

_items[existing.index] = createItem(newAttr);
if (existing) {
_items[existing.index] = item;
} else {
_items.push(item);
}

save();

return item;
emit('added', item);
}

function remove(attr) {
var existing = has(attr);

if (!existing) {
return null;
if (!existing || !emit('remove', existing.item)) {
return;
}

_items.splice(existing.index, 1);
save();
return existing.item;

emit('removed', existing.item);
}

load();
Expand Down
12 changes: 11 additions & 1 deletion test/carty-add-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,16 @@ describe("carty().add", function() {
}.bind(this), undefined, 'Item must be a string or an object with at least an id or label attribute.');
});

it("removes item if quantity lower 0", function() {
instance.add({id: 'Item'});

assert.strictEqual(1, instance.size());

instance.add({id: 'Item', quantity: -1});

assert.strictEqual(0, instance.size());
});

it("compares item", function() {
var attr = {
label: 'label',
Expand All @@ -160,7 +170,7 @@ describe("carty().add", function() {

it("emits add event", function() {
instance.on('add', function(it) {
assert.strictEqual(it, 'Item');
assert.strictEqual(it.id(), 'Item');
});

instance.add('Item');
Expand Down
2 changes: 1 addition & 1 deletion test/carty-remove-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe("carty().remove", function() {

it("emits remove event", function() {
instance.on('remove', function(it) {
assert.strictEqual(it, 'Item');
assert.strictEqual(it.id(), 'Item');
});

instance.remove('Item');
Expand Down

0 comments on commit 9fa4571

Please sign in to comment.