Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.

How to code ranges?

Avatar

Level 2

In quantity discounts, it's pretty common to have the quantity discount vary with the number of items purchased, but not as a fixed percent per item. Example:

Quantity Purchased          Discounted price (each)

1                                        $10

2-4                                     $9

5-8                                     $7

8-10                                   $6

10+                                    $5

For narrow price bands or not too many elements, using a switch statement works OK:

if (Quantity < 10){

    switch(Quantity)

        case "1";

            Price = 10;

        break;

        case "2";

            Price = 9;

        break;

        case "3";

           Price = 9;

        break;

        case "4";

           Price = 9;

        break;

        case "5";

           Price = 7;

         break;

etc.

This seems pretty kludgy and I was wondering if there might be a more elegant way to attack the problem.  An array would work and it's arguably better but still has to have each element put in the array.  Nested if statements get hard to read.  Anyone have a more elegant solution, particularly one that might be easier to maintain?

Thanks in advance!

2 Replies

Avatar

Level 10

Hi,

I am not sure if this is the best solution. An if statement would shorten it a bit and if you put it in a script object, then you would call if from different fields (and only have to maintain it in one location).

if (Quantity.rawValue == 1) {

     Price.rawValue = 10;

} else if (Quantity.rawValue >= 2 && Quantity.rawValue <= 4) {

     Price.rawValue = 9;

} else if (Quantity.rawValue >= 5 && Quantity.rawValue <= 8) {

     Price.rawValue = 7;

} else if (Quantity.rawValue >= 8 && Quantity.rawValue <= 10) {

     Price.rawValue = 6;

} else {

     Price.rawValue = 5;

}

If you have several products with different prices, then you could have function() for each product. Alternatively instead of setting the price against the quantity, you could set a discount against the quantity and then apply this discount across the quantity for each product.

I hope that helps,

N.

Avatar

Level 2

You can also use javascript if else conditions. Sample below:

if(Quantity.rawValue == 1){

Price.rawValue = 10;

}else if(Quantity.rawValue>=2 && Quantity.rawValue<=4){

Price.rawValue = 9;

}else if(Quantity.rawValue>=5 && Quantity.rawValue<=8){

Price.rawValue = 7;

}else if(Quantity.rawValue>=9 && Quantity.rawValue<=10){

Price.rawValue = 6;

}else if(Quantity.rawValue>10){

Price.rawValue = 5;

}

Thanks,

Prasad