Skip to content

Instantly share code, notes, and snippets.

@lennym
Created February 5, 2014 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lennym/8823426 to your computer and use it in GitHub Desktop.
Save lennym/8823426 to your computer and use it in GitHub Desktop.
var Checkout = function Checkout(inventory) {
inventory = inventory || [];
this.basket = {};
this.inventory = {};
inventory.forEach(function (product) {
this.inventory[product.code] = new Product(product);
}.bind(this));
}
Checkout.prototype = {
scan: function (code) {
this.basket[code] = this.basket[code] || 0;
this.basket[code]++;
},
total: function () {
var total = 0;
for (var i in this.basket) {
if (this.basket.hasOwnProperty(i) && this.inventory[i]) {
total += this.inventory[i].getPrice(this.basket[i]);
}
}
return total;
}
}
var Product = function (data) {
this.price = data.price;
this.offer = data.offer;
}
Product.prototype = {
getPrice: function (n) {
if (typeof this.offer === 'function') {
return this.offer(n);
} else {
return n * this.price;
}
}
}
module.exports = Checkout;
var Checkout = require('../checkout');
global.should = require('chai')
.should();
describe('Checkout Class', function () {
it('has a scan method', function () {
var checkout = new Checkout();
checkout.scan.should.be.a('function');
});
it('has a total method', function () {
var checkout = new Checkout();
checkout.total.should.be.a('function');
});
describe('total', function () {
var checkout;
beforeEach(function () {
checkout = new Checkout([
{ code: 'FR1', name: 'Tea', price: 311, offer: function (n) {
return this.price * (Math.floor(n / 2) + n % 2);
} },
{ code: 'SR1', name: 'Strawberries', price: 500, offer: function (n) {
if (n >= 3) {
return n * 450;
} else {
return n * this.price;
}
} },
{ code: 'CF1', name: 'Coffee', price: 1123 }
]);
});
it('test basket 1', function () {
checkout.scan('FR1');
checkout.scan('SR1');
checkout.scan('FR1');
checkout.scan('FR1');
checkout.scan('CF1');
checkout.total().should.equal(2245);
});
it('test basket 2', function () {
checkout.scan('FR1');
checkout.scan('FR1');
checkout.total().should.equal(311);
});
it('test basket 3', function () {
checkout.scan('SR1');
checkout.scan('SR1');
checkout.scan('FR1');
checkout.scan('SR1');
checkout.total().should.equal(1661);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment