tengo un control deslizante que permite al usuario elegir entre 0 y 20000 cómo calcular el precio final con precios por 100 puntos son así:
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$/100ptsEjemplo: el usuario elige entre 3000 y 12000, el precio será 45 $ + 90 $ + 151,2 $ + 200 $ => el precio final será = 486,2 $
si ustedes pueden dar una solución en javascript o estaré bien con una solución algorítmica, gracias
Aquí hay un algoritmo que puede convertir a código:
prices ordenados de forma ascendente de la siguiente manera: [[1200, 2400, 2.2],...]lower y upper .finalPrice inicializada en 0 .lower . Llamemos a este índice i .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 Dado que el control deslizante está restringido a 20000 en la parte superior, puede estar seguro de i nunca se sale de los límites.
Cree una tabla con los umbrales y luego, en JS, itere sobre ella para acumular el precio.
Aquí hay un fragmento ejecutable:
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>