JSFiddle - React, Tailwind, and code Playground
by halirgb
HTML
<p>1 - price: 10$</p>
<p>2000 - price of one: 2$</p>
<p>If more than 2000 - price: 2$</p>
<label>How many would you like
<input type="text" id="quantity" />
<input type="submit" class="calculate" value="calculate">
</label>
JavaScript
function calculate(quantity){
var startPrice = 10; //price of one
var maxOrderCountWherePriceChanges = 2000;
var endPrice = 2; //prico of one @ maxOrderCountWherePriceChanges
// how meny from start to end
var fromStartToEnd = startPrice - endPrice;
var stepIncrementCount = fromStartToEnd / maxOrderCountWherePriceChanges;
var count = maxOrderCountWherePriceChanges;
var endPriceCorected = endPrice - stepIncrementCount;
var prices = [0]; // ocupy the 0 position
while(endPriceCorected <= startPrice){
var price = endPriceCorected += stepIncrementCount;
//console.log(count-- ,price)
prices.push(price);
if(count === 0){
break;
}
}
//console.log(prices); //to get correct value array starts from 0
prices.reverse();
return Math.round(prices[quantity]); // to correct 9.9999999 stuff see originall array to understaind
}
$('.calculate').click(function(e){
e.preventDefault();
var quantity = $('#quantity').val();
var priceAtQuantity = calculate(quantity);
// calculate with same price after 2000
if(quantity > 2000){ // 2000 is max number until price changes
priceAtQuantity = 2; // price at 2000
}
var total = priceAtQuantity * quantity;
alert(total);
})
// $('.awesomeness').html('for' + count + ': ' + price);