Home > Back-end >  how to calculate price using slider [algorithmic problem]
how to calculate price using slider [algorithmic problem]

Time:01-21

i have a slider that let user choose betweent 0 and 20000 how to calculate final price with prices per 100 points are like this :

from 0 to 1200 -> 2.10$/100pts
from 1200 to 2400 ->2.20$/100pts
from 2400 to 4800 ->2.5$/100pts
from 4800 to 7200 ->3.75$/100pts
from 7200 to 10000 ->5.4$/100pts
from 10000 to 20000 ->10$/100pts

Example : user choose from 3000 to 12000 price will be 45$ 90$ 151.2 $ 200 $ => final price will be = 486.2 $

if you guys can give solution in javascript or i will be fine with algoritmic solution , thanks

CodePudding user response:

Here's an algorithm that you can convert to code:

  1. Let's have a nested array, or an array of price objects (it's important to be indexable and sorted ascending), for prices called prices sorted ascending as follows:
[[1200, 2400, 2.2],...]
  1. Let's have the lower and upper bounds of user input in variables lower and upper.
  2. Let's have a variable finalPrice initialized to 0.
  3. Find the index of the first element in prices where its upper bound is > lower. Let's call this index i.
  4. Now run while lower < upper:
// calc the cost of this range
finalPrice  =  (min(prices[i][1], upper) - lower)/100 * prices[i]
// sets `lower` to the upper bound of the previous price,
// since we already calculated that.
lower = min(prices[i][1], upper) 
// increment i to calc with the next price range
i  = 1

Since the slider is constraint to 20000 on the upper side, you can be sure that i never goes out of bounds.

CodePudding user response:

Create a table with the thresholds and then in JS iterate over it to accumulate the price.

Here is a runnable snippet:

const table = [
    [10000, 10.00],
    [ 7200,  5.40],
    [ 4800,  3.75],
    [ 2400,  2.50],
    [ 1200,  2.20],
    [    0,  2.10],
];

function convert(points) {
    let total = 0;
    for (let [limit, price] of table) {
        if (points > limit) {
             total  = Math.floor((points - limit) / 100) * price;
             points = limit;
        }
    }
    return total;
}

// IO handling
let [rngStart, rngEnd] = document.querySelectorAll("input");
let output = document.querySelector("span");
rngStart.addEventListener("input", refresh);
rngEnd.addEventListener("input", refresh);


function refresh() {
    let start =  rngStart.value;
    let end =  rngEnd.value
    output.textContent = (convert(end) - convert(start)).toFixed(2);
}
refresh();
input[type=range] { width: 80% }
From: <input type="number" min="0" max="20000" step="100" value="3000">
To: <input type="number" min="0" max="20000" step="100" value="12000">

Price: <span></span>

  •  Tags:  
  • Related