how to calculate price using slider [algorithmic problem]
Solution 1:
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>
Solution 2:
Here's an algorithm that you can convert to code:
- 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],...]
- Let's have the lower and upper bounds of user input in variables
lower
andupper
. - Let's have a variable
finalPrice
initialized to0
. - Find the index of the first element in prices where its upper bound is >
lower
. Let's call this indexi
. - 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.