Skip to content

Instantly share code, notes, and snippets.

@luisfarzati
Forked from odino/desc.md
Last active August 29, 2015 13:56
Show Gist options
  • Save luisfarzati/9183313 to your computer and use it in GitHub Desktop.
Save luisfarzati/9183313 to your computer and use it in GitHub Desktop.
My submission for the Namshi coding challenge.

Coding challenge: cartified!

✔ the cart needs to be implemented as an AngularJS service

✔ the cart should be retrieved from the localStorage, where it's stored under the key cart

✔ every time an action is performed on the cart, it should be persisted on the localStorage

✔ the cart should only know about item IDs and their quantity

✔ you will write the cart by implementing the methods of the provided cart service in the template.js file contained in this gist: please fork it and submit your implementation

✔ it should take you less than 1 hour to come up with an implementation, but we won't put any time limit for this challenge

What are we going to look for?

  • the fewer lines of code, the better
  • clear, coincise, DRY implementation
  • appropriate naming conventions

Another thing to consider: the cart should be working even when the user has multiple browser tabs open and is adding products from each of them.

angular.module('services.cart', [])
.service('Cart', ['$rootScope', 'Reviewer', function ($rootScope, Reviewer) {
var cart = JSON.parse(localStorage.cart || '{}');
var getCart = this.getCart = function () {
return angular.extend({}, cart);
};
var addItem = this.addItem = function (id) {
(cart[id] || (cart[id] = { quantity: 0 })).quantity++;
save();
};
var addItems = this.addItems = function (ids) {
ids.forEach(addItem);
save();
};
// Checks if the cart can be persisted through the Reviewer service: if so, it persists it.
var save = function () {
Reviewer.review(cart).then(function (approved) {
approved && persist();
});
};
var remove = this.remove = function (id) {
delete cart[id] && save();
};
// Empties the cart
var clear = this.clear = function () {
cart = {} && save();
};
// Persist the cart on the localStorage
var persist = function () {
localStorage.cart = JSON.stringify(cart);
refresh();
};
// Changes the quantity of one of the items in the cart.
var changeQuantity = this.changeQuantity = function (id, quantity) {
cart[id].quantity = quantity;
save();
};
// Notifies the application that the cart has been persisted, so that other parts of the app
// can modify themselves based on the latest cart update.
var refresh = function () {
$rootScope.$broadcast('updatedCart');
};
angular.element(window).on('storage', function (e) {
if (e.key !== 'cart') return;
$rootScope.$apply(function () {
cart = JSON.parse(localStorage.cart);
refresh();
});
});
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment