Created
June 7, 2011 11:03
-
-
Save olostan/1012036 to your computer and use it in GitHub Desktop.
POS terminal (JS solution)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Helper function: | |
Object.prototype.objReduce = function (func,initial) { for(x in this) if (this[x]|0==this[x]) initial = func(x,this[x],initial); return initial; }; | |
var pricelist = { A: { price: 1.25, pack: 3, ppack: 3}, B: { price: 4.25 }, C: { price: 1, pack:6,ppack:5}, D: {price: 0.75} } | |
// Collect array of items into object with fields of items and values of number of selled items. | |
// Example: A A B => { A: 2, B: 1 } | |
var collectItems = function(items) { | |
return items.reduce(function(y,x) { if (y[x]) { y[x]++} else {y[x]=1}; return y;},{}); | |
}; | |
// Calculate price for 'value' items 'name' using pricelist | |
var calcPrice = function(name, value, pricelist) { | |
return pricelist[name].pack? | |
// if we have volume discount | |
(pricelist[name].ppack*(~~(value/pricelist[name].pack))+pricelist[name].price*(value%pricelist[name].pack)) | |
// without volume discount | |
:(pricelist[name].price*value); | |
}; | |
// collect items and calcualte prices for them | |
var POS = function(items,pricelist) { return collectItems(items).objReduce(function(n,v,i) { return i+calcPrice(n,v,pricelist); },0);} | |
console.log(POS(['A','B','C','D','A','B','A'],pricelist)); // -> 13.25 | |
console.log(POS(['A','B','C','D'],pricelist)); // -> 7.25 | |
console.log(POS(['C','C','C','C','C','C','C'],pricelist)); // -> 6 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Helper function: | |
Object.prototype.objReduce = function (func,initial) { for(x in this) if (this[x]|0==this[x]) initial = func(x,this[x],initial); return initial; }; | |
var pricelist = { A: { price: 1.25, pack: 3, ppack: 3}, B: { price: 4.25 }, C: { price: 1, pack:6,ppack:5}, D: {price: 0.75} } | |
var POS = function(items) { return items.reduce(function(y,x) { if (y[x]) { y[x]++} else {y[x]=1}; return y;},{}).objReduce(function(n,v,i) { return i+(pricelist[n].pack?(pricelist[n].ppack*(~~(v/pricelist[n].pack))+pricelist[n].price*(v%pricelist[n].pack)):(pricelist[n].price*v)); },0);} | |
console.log(POS(['A','B','C','D','A','B','A'])); // -> 13.25 | |
console.log(POS(['A','B','C','D'])); // -> 7.25 | |
console.log(POS(['C','C','C','C','C','C','C'])); // -> 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment