JSFiddle - React, Tailwind, and code Playground
JavaScript
var Catalogue, Chooser, Item;
Item = (function() {
function Item(size, price) {
this.size = size;
this.price = price;
return;
}
return Item;
})();
Chooser = (function() {
function Chooser(catalogue, request) {
this.request = request;
this.items = catalogue[this.request.name];
return;
}
Chooser.prototype.choose = function() {
console.debug("Choosing " + this.request.size + " from", this.items.slice());
return this.chooseItems(this.request.size, this.items.slice());
};
Chooser.prototype.chooseItems = function(count, items) {
console.debug("count", count);
console.debug("items", items);
console.debug("@items", this.items);
this.stash = [];
try {
this.gatherItems(count, items);
return this.stash;
} catch (_error) {
items.shift();
if (items.length === 0) {
throw new Error("Can't gather Items");
}
return this.chooseItems(count, items);
}
};
Chooser.prototype.gatherItems = function(count, items) {
var allowed, c, item;
allowed = this.trimItems(count, items);
item = allowed[0];
c = count / item.size;
this.stash.push({
count: count,
item: item
});
if (count % bundle.size !== 0) {
this.gatherItems(count - c * bundle.size, allowed);
}
};
Chooser.prototype.trimItems = function(count, items) {
var allowed;
allowed = items.filter(function(item) {
return item.size > count;
});
if (allowed.length === 0) {
throw new Error();
}
return allowed;
};
return Chooser;
})();
Catalogue = {
a: [new Item(10, 1000), new Item(5, 600)],
b: [new Item(11, 1000), new Item(5, 600), new Item(2, 400)]
};
new Chooser(Catalogue, {
name: 'a',
size: 10
}).choose();