Develop a decreasing price function by step - javascript

I'm trying to configure my price list. The price unit must decrease depending the quantity you buy but should keep growing.
I was able to do it in excel, but now I would like to do a function in javascript.
my pricelist in the DB is like this:
min max price
1 9 50
10 19 45
20 29 40
30 49 35
50 79 30
80 90 25
The function depending the price is
qty price function
1-9 qty*50
10-19 (qty-9)*45+(9*50)
20-29 (qty-19)*40+(19*45)
...
80-90 (qty-79)*25+(79*30)
I would like to create a ES6 function that receive the quantity in parameter and return the total price.
UPDATE
I was able to create the function but I'm pretty sure that we can improve it.
let priceList= [
{"_id":1,"min":1,"max":9,"price":50},
{"_id":2,"min":10,"max":19,"price":45},
{"_id":3,"min":20,"max":29,"price":40},
{"_id":4,"min":30,"max":49,"price":35},
{"_id":5,"min":50,"max":79,"price":30},
{"_id":6,"min":80,"max":90,"price":25}
]
function sum(qty){
let sum = 0;
let prices = priceList.filter((x)=>x.min<=qty);
var price;
var priceArr=[];
const pricesLength = prices.length;
for (let i = 0; i < pricesLength ; i++) {
price = prices[i];
if(i==0){
priceArr.push(price.price * ((price.max < qty) ? price.max : qty));
} else {
priceArr.push(price.price * ((price.max <= qty) ? price.max - price.min + 1 : qty - price.min + 1) + priceArr[i-1]);
}
}
return priceArr[pricesLength-1];
}
https://jsfiddle.net/jm7teuqb/1/

Related

Input Checkbox Only Updates One Value But Other Inputs Don't Update?

So I have this app I made where it calculates the menu items total and includes a $5 delivery fee. The problem is the 4th option only includes the $5 fee in the total, but the other 3 options don't include the fee
Here's my codepen
https://codepen.io/shodoro/pen/dydNopX
Why is my 4th option, the smoothie $4 the only input checkbox that adds the delivery fee correctly?
The first 3 options don't include the $5 delivery fee in the total and I don't know how to fix it
Here's my JS
function updatePrice() {
let items = 0;
let deliveryFee = document.getElementById('fee')
let tax = document.getElementById('tax')
let tip = document.getElementById('tip')
tax = .1
tip = .2
document.querySelectorAll('input[type=checkbox]').forEach(checkBox => {
if (checkBox.checked) {
items += +checkBox.value
deliveryFee = 5
} else {
deliveryFee = 0
}
})
document.getElementById("price").textContent = `Food Total: $${(items).toFixed(2)}`;
document.getElementById("tax").textContent = `Tax (10%): $${(items * tax).toFixed(2)}`;
document.getElementById("tip").textContent = `Tip (20%): $${(items * tip).toFixed(2)}`;
document.getElementById("total").textContent = `Your order total is: $${((items * tax)+(items * tip)+(items)+(deliveryFee)).toFixed(2)}`;
}
Essential I want all options to include the delivery fee when clicking them, but also making sure the delivery fee resets to 0 whenever you uncheck all options.
That's because you are setting deliveryFee in a loop and so if, for example, the 12 piece wings item is checked, then it sets deliveryFee to 5 and then it's going to loop through to the next item (6 piece wings) and it will set deliveryFee to 0. So when it gets to the calculation for the total, it deliveryFee will be 0 and not 5. I think maybe you want something more like this:
function updatePrice() {
console.log('updatePrice');
let items = 0;
let deliveryFee = 0;
let tax = document.getElementById('tax')
let tip = document.getElementById('tip')
tax = .1
tip = .2
console.log('before forEach loop', items, deliveryFee);
document.querySelectorAll('input[type=checkbox]').forEach(checkBox => {
console.log(checkBox);
if (checkBox.checked) {
console.log('checked!')
items += +checkBox.value
if (deliveryFee == 0) {
console.log('First checked item, setting delivery fee to 5.')
deliveryFee = 5;
}
} else {
console.log('not checked!');
}
})
console.log('after forEach loop', items, deliveryFee);
if (items >= 10) {
deliveryFee = deliveryFee * 2;
}
let orderTotal = (items * tax)+(items * tip)+(items) + deliveryFee;
document.getElementById("price").textContent = `Food Total: $${(items).toFixed(2)}`;
document.getElementById("tax").textContent = `Tax (10%): $${(items * tax).toFixed(2)}`;
document.getElementById("tip").textContent = `Tip (20%): $${(items * tip).toFixed(2)}`;
document.getElementById("fee").textContent = `Delivery Fee: $${deliveryFee.toFixed(2)}`;
document.getElementById("total").textContent = `Your order total is: $${orderTotal}`;
}

JavaScript function won't run twice with different inputs

I'm trying to make this function run twice with two different inputs, but it only runs once.
the code:
const data1dolphins = 44 + 23 + 71;
const data1Koalas = 65 + 54 + 49;
const data2dolphins = 85 + 54 + 41;
const data2Koalas = 23 + 34 + 27;
function calcAverage(data, dataValue) {
const scoreAverage = data * dataValue
return scoreAverage;
}
const data1DolphinsAverage = calcAverage(data1dolphins, 3)
const data1KoalasAverage = calcAverage(data1Koalas, 3)
const data2DolphinsAverage = calcAverage(data2dolphins, 3)
const data2KoalasAverage = calcAverage(data2Koalas, 3)
function checkWinner(avgTeamOne, avgTeamTwo) {
if (avgTeamOne >= (avgTeamTwo * 2)) {
console.log(`team one won with average score of : ${avgTeamOne}, while team two lost with average score of : ${avgTeamTwo}`)
} else if (avgTeamTwo >= (avgTeamOne * 2)) {
console.log(`team two won with average score of : ${avgTeamTwo}, while team one lost with average score of : ${avgTeamOne}`)
}
// console.log('testing round')
}
console.log('before')
checkWinner(data1DolphinsAverage, data1KoalasAverage)
console.log('middle')
checkWinner(data2DolphinsAverage, data2KoalasAverage)
console.log('after')
the output:
before
team one won with average score of : 540, while team two lost with average score of : 252
middle
after
Have you tried an else statement?
function checkWinner (avgTeamOne,avgTeamTwo){
if(avgTeamOne >= (avgTeamTwo*2)) {
console.log(`team one won with average score of : ${avgTeamOne}, while team two lost with average score of : ${avgTeamTwo}`);
} else if (avgTeamTwo >= (avgTeamOne*2)){
console.log(`team two won with average score of : ${avgTeamTwo}, while team one lost with average score of : ${avgTeamOne}`);
} else { <<
console.log("neither of these things happened."); <<
} <<
}
I find it a bit hard to see your purpose, as you didn't provide values for data1dolphins, data1Koalas, data2dolphins, or data2Koalas, but I'm guessing that this is the fix that you need.
the function ran fine after adding an else statment:
const data1dolphins = 44+23+71;
const data1Koalas = 65+54+49;
const data2dolphins = 85+54+41;
const data2Koalas = 23+34+27;
function calcAverage (data,dataValue){
const scoreAverage = data * dataValue
return scoreAverage;
}
const data1DolphinsAverage = calcAverage(data1dolphins,3)
const data1KoalasAverage = calcAverage(data1Koalas,3)
const data2DolphinsAverage = calcAverage(data2dolphins,3)
const data2KoalasAverage = calcAverage(data2Koalas,3)
function checkWinner (avgTeamOne,avgTeamTwo){
if(avgTeamOne >= (2*avgTeamTwo)) {
console.log(`team one won with average score of : ${avgTeamOne}, while team two lost with average score of : ${avgTeamTwo}`)
} else if (avgTeamTwo >= (2*avgTeamOne)){
console.log(`team two won with average score of : ${avgTeamTwo}, while team one lost with average score of : ${avgTeamOne}`)
}else {
console.log('none of the above')
}
}
console.log('before')
checkWinner(data1DolphinsAverage, data1KoalasAverage)
console.log('middle')
checkWinner(data2DolphinsAverage, data2KoalasAverage)
console.log('after')

Waterpay calculator else if statements

I've been going over this question now for a couple of days and I'm still no closer to getting it right or understanding as to how to get it to run properly.
This is the current code I have:
let waterPay = prompt("Please enter the amount of water you use to get a price you need to pay, thank you!");
if (waterPay < 6000) {
console.log("The number is below 6000");
console.log (waterPay / 1000); //The outcome of this must be saved as a different let
console.log (waterPay * 15.73);// outcome of the above times by this amount
}
else if (waterPay > 6000 && waterPay <= 10500) {
console.log("The number is between 6000 and 10500");
}
else if (waterPay > 10500 && waterPay <= 35000) {
console.log("The number is between 10500 and 35000");
}
else if (waterPay > 35000) {
console.log("The number is above 35000");
}
What my code needs to do is take an input from the user stating how many litres of water they use, you can see in the code that depending on the amount of litres they use it should print out how much they owe.
The table above states that the first 6 000 litres will cost R15.73 per kilolitre.
Next, water consumption above 6 000 litres but below 10 500 litres will be
charged at R22.38 per kilolitre. Therefore, a household that has used 8000
litres will pay R139.14 (15.73 x 6 + 22.38 x 2). The table carries on in this
manner.
Im battling to figure out how I should go about working this out. Any help would be appreciated.
The data structure needed is something that pairs rates with usage thresholds. The last threshold is effectively infinite, to catch any usage above the highest. The logic is to find() the right rate object and multiply that rate tier's rate by the usage.
let rateData = [{
upTo: 6000,
rate: 15.73
},
{
upTo: 10500,
rate: 22.38
},
{
upTo: 35000,
rate: 34.0. // made this one up, not in the OP
},
{
upTo: Number.MAX_SAFE_INTEGER,
rate: 50.0. // made this one up, not in the OP
}
];
function rateDatumForUsage(usage) {
return rateData.find(r => usage <= r.upTo);
}
function costForUsage(usage) {
const rateDatum = rateDatumForUsage(usage);
return usage * rateDatum.rate;
}
console.log(`The cost of using 5000 units is (15.73*5000) ${costForUsage(5000)}`)
console.log(`The cost of using 10000 units is (22.38*10000) ${costForUsage(10000)}`)
console.log(`The cost of using 100000 units is (50*100000) ${costForUsage(100000)}`)
Total cost should be calculated by steps.
This means that, for example, if the first 10 liters cost USD 2, the following 10 liters (from 10 to 20) cost USD 1 and from 20 cost will be USD 0.5, then the total cost for 30 liters will be: 10*2 + 10*1 + 10*0.5 = 35.
This can only be achieved generically by looping. Here is the code:
const steps = [
6000,
10500,
35000
];
const rates = [
10,
20,
30
];
function calculate(used) {
let output = 0;
for (let i = 0; i < steps.length; i++) {
if (used >= steps[i]) {
output += steps[i] * rates[i];
} else {
output += (used - (steps[i - 1] || 0)) * rates[i];
break;
}
}
return output;
}
console.log(calculate(3000));
console.log(calculate(6000));
console.log(calculate(9000));
console.log(calculate(50000));

Select random winner with percentages

I would want to select a random winner from about 2 - 10 players.
Every player have precent chance to win. Someone have 50% and someone 10%.
Let's say we have 2 players. One player have 20% and other have 80%. How do I select winner between these two?.
Players are in array
var players = {
player1: {
chance: 20 //%
}
player2: {
chance: 80 //%
}
}
//Select winner from json
(Assuming the percentages all add up to 100)
You would first have to order the players. Then take a random number from 1 to 100, and find out which player that random number falls under.
For example:
// Modified json to array so we can easily loop through them
// If you would like help turning the json to an array, I can provide code for that upon request
var players = [
{
chance: 20
},
{
chance: 40
},
{
chance: 40
}
];
// Generate random number
var perc = Math.random() * 100; // between 0 and 99.999~
// Save where we are in the percentage
var currentPerc = 0;
// Loop through the players and check who the random number chose
for ( var pID = 0; pID < players.length; pID++ ) {
// Check if the current player we are looking at has won
if (perc < (players[pID].chance + currentPerc)) {
alert("PLAYER " + (pID + 1) + " HAS WON.");
// Do player winning code here
break; // break out of the loop, we're done
} else {
currentPerc += players[pID].chance;
}
}
In the above example, imagine that the random number chose 45 (0.45 * 100 since math.random gives us 0.0 to 0.99~).
This would mean that player 2 won
0 to 20 = Player 1 wins
21 to 60 = Player 2 wins
61 to 100 = Player 3 wins
Using 45 as the random number chosen The first iteration, we check if player 1 has won. He has not, so we add player 1's percentage to the "current percentage".
Then in the second iteration we check player 2. Since 45 < (20 + 40), player 2 has won chosen. We alert that he has won and will do some code for that.
var players = [20,5,15,40,20];
var getWinner = function(players){
var random = Math.random();
var sum = 0;
for(var i = 0; i < players.length; i++){
sum+= players[i]/100;
if(random<= sum) return i;
}
}
Returns the number of the player(index 0) who wins

Javascript function that calculates based on increments

I need assistance creating a javascript function that performs the below logic.
If cubic ft is between 2500-5000 invoice $42, but if greater than 5000 then invoice $42 plus $22 per 1000 cubic ft.
Here is what I have so far:
var assessfee = function(cubicft) {
if (cubicft > 2500 || cubicft <= 5000) {
console.log($42);
} else if (cubicft > 5000) {
var diff = cubicft - 5000;
}
}
Something like this? Basically that sets the price to 42 since that is the default price and if cubicft is > 5000 it takes that divided by 1000 then takes it times 22 and adds that value to price. Finally it prints it to the console.
var assessfee = function(cubicft) {
var price = 42;
if (cubicft > 5000) {
price += (cubicft-5000)/1000*22;
}
console.log("$" + price);
}

Categories

Resources