Skip to content

Instantly share code, notes, and snippets.

@acodeninja
Created January 14, 2020 17:17
Show Gist options
  • Save acodeninja/3954d4732926c0bd84e2f62c9382f9c4 to your computer and use it in GitHub Desktop.
Save acodeninja/3954d4732926c0bd84e2f62c9382f9c4 to your computer and use it in GitHub Desktop.
ukef-code-test-nodejs
module.exports = class Checkout {
constructor(pricing_rules) {
this.pricing_rules = pricing_rules;
this.items = [];
}
scan(item) {
if (! Object.keys(this.pricing_rules).includes(item)) {
throw new Error("not in the rules");
}
this.items.push(item);
}
total() {
const invoice = {};
let running_total = 0;
this.items.forEach((product) => {
if (!invoice[product]) {
invoice[product] = 1;
} else {
invoice[product] += 1;
}
});
Object.keys(invoice).forEach((key) => {
let count = invoice[key];
let price_points = Object.keys(this.pricing_rules[key]).sort().reverse();
price_points.forEach(point => {
if (count >= point) {
running_total += this.pricing_rules[key][point];
}
return false;
});
});
return running_total;
}
};
const Checkout = require('./Checkout');
describe('creating a new instance of Checkout', () => {
it('takes a set of pricing rules', () => {
const checkout = new Checkout({});
expect(checkout).toHaveProperty('pricing_rules');
});
it('exposes a scan method', function () {
const checkout = new Checkout({});
expect(checkout.scan).not.toBeUndefined();
});
it('exposes a total method', function () {
const checkout = new Checkout({});
expect(checkout.total).not.toBeUndefined();
});
});
describe('scanning a single item and totalling the order', () => {
it('allows for a single item to be given in the pricing rules', function () {
const checkout = new Checkout({
item: {
1: 2.00
}
});
checkout.scan('item');
expect(checkout.items).toEqual(['item']);
});
});
describe('scanning a single item not in the rules', () => {
it('fails', function () {
const checkout = new Checkout({
item: {
1: 2.00
}
});
expect(() => {
checkout.scan('thing')
}).toThrow()
});
});
describe('scanning a single item and totalling the cost', () => {
it('returns the price correctly', function () {
const checkout = new Checkout({
item: {
1: 2.00
}
});
checkout.scan('item');
expect(checkout.total()).toEqual(2.00);
});
});
describe('scanning an item twice and applying a discount', () => {
it('returns the price correctly', function () {
const checkout = new Checkout({
item: {
1: 2.00,
2: 1.00
},
});
checkout.scan('item');
checkout.scan('item');
expect(checkout.total()).toEqual(3.00);
});
});
// last test currently fails.
describe('scanning an item thrice and applying a discount', () => {
it('returns the price correctly', function () {
const checkout = new Checkout({
item: {
1: 2.00,
2: 1.00,
},
});
checkout.scan('item');
checkout.scan('item');
checkout.scan('item');
expect(checkout.total()).toEqual(4.00);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment