Calculate backwards in a Javascript array

2019-09-11 15:27发布

问题:

Heres my currently working JsFiddle.

I have 2 products 1 and 2

Then I have 3 STYLES for those products a user MUST select : s1,s2 and s3

Then I have table of prices that changes with the quantity and style people choose. See below

This is my array.

Quantity

Quantity : [ 50, 100, 150, 200, 250]

Product 1 prices for all 3 styles

p1s1 : [2.00, 1.80, 1.60, 1.40, 1.20] p1s2 : [2.10, 2.00, 1.80, 1.60, 1.40] p1s3 : [2.25, 2.15, 2.05, 1.95, 1.75]

Product 2 prices for all 3 styles

p2s1 : [3.00, 2.80, 2.60, 2.40, 2.20] p2s2 : [3.10, 3.00, 2.80, 2.60, 2.40] p2s3 : [3.50, 3.30, 3.00, 2.80, 2.50]

Heres my currently working JsFiddle.

My question

I want to create a new calculator that works backwards. That is, when someone inputs the amount of money they have in hand, let's say $250, the calculator should display how many (quantity) Product 1s and 2s someone can purchase with that money. So it should display like below.

Product 1, Style 1 - Qty 150 = $240

Product 1, Style 2 - Qty 138 = $248.40

Product 1, Style 3 - Qty 121 = $248.05

Let me know if Im not clear. Thanks so much in advance.

回答1:

function getAffordibiltyObject(OB, money)
{
    var afford = {};
    for (var code in OB){
        if(/p\ds\d/.test(code)){
            for (var i=0; i<OB[code].length; i++){
                if(money < OB[code][i]*OB.qtty[i] || i==OB[code].length-1){
                    var price = OB[code][i];
                    var quantity = Math.floor(money/price);
                    var total = quantity*price;
                    afford[code] = [quantity, total];
                }
            }
        }
    }

    return afford;
}


var OB = {
    wrap : 0.05,
    // quantities
    qtty : [  50,  100,  150,  200,  250],
    // product 1
    p1s1 : [2.00, 1.80, 1.60, 1.40, 1.20],
    p1s2 : [2.10, 2.00, 1.80, 1.60, 1.40],
    p1s3 : [2.25, 2.15, 2.05, 1.95, 1.75],
    // product 2
    p2s1 : [3.00, 2.80, 2.60, 2.40, 2.20],
    p2s2 : [3.10, 3.00, 2.80, 2.60, 2.40],
    p2s3 : [3.50, 3.30, 3.00, 2.80, 2.50]
};

var money = 250;


var affordibilityOB = getAffordibiltyObject(OB, money);

This is what you are looking for affordibilityOB will be an object with keys like p1s1 , p2s2 ... and the values will be an array of length two first element being result quantity and second being result total.