JavaScript array find fitting range -
i have following array 2 objects:
var myarr = [{ id: 3, licences: 100 new_value_pr_licence: 40 }, { id: 4, licences: 200 new_value_pr_licence: 25 }]
a user wish buy 150 licences. means fall category 100 because above 100 licences below 200 means pay $40 per licence.
note array object values varies.
order plans price per licence:
myarr.sort(function (a, b) { return a.new_value_pr_licence - b.new_value_pr_licence; })
then starting start of array, take many of plan can without going on number user wants buy:
var numuserwants = 150; var purchases = {}; var cheapestavailableproduct = myarr.shift(); while (numuserwants > 0 && cheapestavailableproduct) { if (numuserwants <= cheapestavailableproduct.licences) { purchases[cheapestavailableproduct.id] = math.floor(cheapestavailableproduct.licences / numuserwants); numuserwants = cheapestavailableproduct.licences % numuserwants; } cheapestavailableproduct = myarr.shift(); }
at point, purchases
map of plan id number:
purchases => { 3: 3 4: 1 }
this doesn't handle case over-purchasing cheapest option (eg: it's cheaper buy 160 @ 4x40
, instead of 150 @ 3x40 + 1x25 + 1x5
), it's start tweaking.
Comments
Post a Comment