Simplifying multiple similar If statements (JAVASCRIPT) - javascript

Im working on a code for an adobe acrobat form, I want to add the following code:
var total =6301
var warranty
if (0 < total && total <= 3300){warranty = 194.25}
else if (3300 < total && total <= 4000){warranty = 197.5}
else if (4000 < total && total <= 5000){warranty = 202.15}
else if (5000 < total && total <= 6000){warranty = 206.75}
else if (6000 < total && total <= 7000){warranty = 211.45}
else if (7000 < total && total <= 8000){warranty = 216.1}
else if (8000 < total && total <= 9000){warranty = 220.75}
else if (9000 < total && total <= 10000){warranty = 225.4}
else if (10000 < total && total <= 11000){warranty = 230.1}
else if (11000 < total && total <= 12000){warranty = 234.75}
else if (12000 < total && total <= 13000){warranty = 239.4}
else if (13000 < total && total <= 14000){warranty = 243.95}
else if (14000 < total && total <= 15000){warranty = 248.7}
else if (15000 < total && total <= 16000){warranty = 253.3}
else if (16000 < total && total <= 17000){warranty = 258}
else if (17000 < total && total <= 18000){warranty = 262.65}
else if (18000 < total && total <= 19000){warranty = 267.3}
else if (19000 < total && total <= 20000){warranty = 271.95}
else if (20000 < total && total <= 21000){warranty = 276.6}
else if (21000 < total && total <= 22000){warranty = 281.3}
else if (22000 < total && total <= 23000){warranty = 285.9}
else if (23000 < total && total <= 24000){warranty = 290.5}
else if (24000 < total && total <= 25000){warranty = 295.25}
else if (25000 < total && total <= 26000){warranty = 299.85}
else if (26000 < total && total <= 27000){warranty = 304.55}
else if (27000 < total && total <= 28000){warranty = 309.15}
else if (28000 < total && total <= 29000){warranty = 313.85}
else {warranty = 999999}
I want to have this be a lot less repetitive as I have a lot more conditions similar to the ones above.
Thanks for the help in advance!!

This approach features an array with value pairs which works for any values.
const
getValue = total => [
[3300, 194.25], [4000, 197.5], [5000, 202.15], [6000, 206.75],
[7000, 211.45], [8000, 216.1], [9000, 220.75], [10000, 225.4],
[11000, 230.1], [12000, 234.75], [13000, 239.4], [14000, 243.95],
[15000, 248.7], [16000, 253.3], [17000, 258], [18000, 262.65],
[19000, 267.3], [20000, 271.95], [21000, 276.6], [22000, 281.3],
[23000, 285.9], [24000, 290.5], [25000, 295.25], [26000, 299.85],
[27000, 304.55], [28000, 309.15], [29000, 313.85], [Infinity, 999999]
].find(([t]) => total <= t)[1];
console.log([0, 1, 3300, 3500, 3999, 4000, 4001, 5000, 10000, 100000].map(getValue));

Use switch case instead which is ideal in terms of optimisation & performance. This way the code execution directly jumps into the corresponding condition rather than going through each if else if condition.
var total = 6301;
var warranty;
switch (true) {
case (0 < total && total <= 3300): warranty = 194.25; break;
case (3300 < total && total <= 4000): warranty = 194.25; break;
...
default: warranty = 999999; break;
}

Related

I want to check the grade of the students marks , based on average

What's wrong with this code? I tried get marks using array and pass the array in to function parameters and calculate the average in that function.
const marks = [100,100,80];
var summ = 0;
function calculateGrade(){
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}
console.log(calculateGrade(marks));
const sum = marks.reduce((partialSum, a) => partialSum + a, 0);
const marks = [100, 100, 80];
var summ = 0;
//issue one (Tmarks were missing )
function calculateGrade(Tmarks) {
// issues 2 ( <= should be < )
for (let i = 0; i < Tmarks.length; i++) {
summ += Tmarks[i];
}
var avg = summ / Tmarks.length;
if (avg <= 59) {
console.log("F");
} else if (avg >= 60 && avg <= 69) {
console.log("D");
} else if (avg >= 70 && avg <= 79) {
console.log("C");
} else if (avg >= 80 && avg <= 89) {
console.log("B");
} else if (avg >= 90 && avg <= 100) {
console.log("A");
}
}
console.log(calculateGrade(marks));
Following were the issues in your code
You were not getting the parameters in function definition
issues 2 ( <= should be < )
You just added an extra = in your for loop
i<=marks.length
instead of
i<marks.length
So while calculating the sum & average, a garbage value gets added up.
You are very close
const marks = [100, 100, 80];
function calculateGrade(marks) {
let summ = 0;
for (let i = 0; i < marks.length; i++) {
summ += marks[i];
}
const avg = summ / marks.length;
let grade = '';
if (avg < 59) {
grade = 'F';
} else if (avg <= 69) {
grade = 'D';
} else if (avg <= 79) {
grade = 'C';
} else if (avg <= 89) {
grade = 'B';
} else {
grade = 'A';
}
return grade;
}
console.log(calculateGrade(marks));
There are couple of mistakes in your code.
1.
for(let i=0; i<=marks.length;i++)
marks.length is 3. Array index starting from 0.
const marks = [100,100,80];
index 0 is 100.
index 1 is 100.
index 2 is 80.
When you add i<=marks.length, this is equals to i<=3.
= in here will run the loop extra circle and this will return NaN because there are only 3 elements in you array and array indexing is 0 based.
2.
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
avg is out of scope. you have defined avg inside the loop and trying to access it outside of the loop. Anything declared in the loop is scoped to that loop and are not available outside the loop.
3.
console.log(calculateGrade(marks));
Your calculateGrade() function is not accepting any parameters. So you can't pass any parameter into this function.
4.
console.log(calculateGrade(marks));
since calculateGrade() function is not returning any value, this will print nothing. So you don't need to call this inside a console.log();.
I have simplified your code as below.
const marksArr = [100, 100, 80];
calculateGrade(marksArr);
function calculateGrade(marks) {
console.log('calling calculateGrade(marks)...');
var avg = (marksArr.reduce(function(a, b) {
return a + b;
}, 0)) / marksArr.length;
console.log('avg is', avg);
if (avg <= 59) {
console.log('Grade', 'F');
} else if (avg >= 60 && avg <= 69) {
console.log('Grade', 'D');
} else if (avg >= 70 && avg <= 79) {
console.log('Grade', 'C');
} else if (avg >= 80 && avg <= 89) {
console.log('Grade', 'B');
} else if (avg >= 90 && avg <= 100) {
console.log('Grade', 'A');
}
}
` calculateGrade(){
let marks = [100,100,80];
let summ = 0;
let avg = 0;
for(let i = 0; i < marks.length; i++){
summ = summ+marks[i];
avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}`
> array start from 0

Problem with Javascript function not returning total sum in a for loop with if conditions

I am writing pure javascript without any HTML and I am having trouble with one of my functions that would need to return the total "course points."
The program consists of prompting the user the # of course taken followed by the grade received which is pushed in the "grades" array. The function calculateCP will allow it to reiterate every element of the array and is suppose to give me the total course points given the following if conditions.
Please help why my function isn't working! The output is returning only the first element of the array, not the total sum of all elements.
calculateCP = () => {
let coursePoints;
let total = 0;
for (let i = 0; i < grades.length; i++) {
if (grades[i] >= 90) {
coursePoints = 4;
} else if (grades[i] >= 80 && grades[i] < 90) {
coursePoints = 3;
} else if (grades[i] >= 70 && grades[i] < 80) {
coursePoints = 2;
} else if (grades[i] >= 60 && grades[i] < 70) {
coursePoints = 1;
} else if (grades[i] < 60) {
coursePoints = 0;
}
return total = total + coursePoints;
}
}
const grades = [];
let noOfCourses = parseInt(prompt("Please enter # of courses taken: "));
console.log("\n")
for (let i = 0; i < noOfCourses; i++) {
grades.push(prompt('Enter grade recieved '));
}
console.log(calculateCP());
}
In the for loop you just want to sum the values.. only once you're done, return the total :) something like this..
calculateCP = () => {
let coursePoints;
let total = 0;
for (let i = 0; i < grades.length; i++) {
if (grades[i] >= 90) {
coursePoints = 4;
} else if (grades[i] >= 80 && grades[i] < 90) {
coursePoints = 3;
} else if (grades[i] >= 70 && grades[i] < 80) {
coursePoints = 2;
} else if (grades[i] >= 60 && grades[i] < 70) {
coursePoints = 1;
} else if (grades[i] < 60) {
coursePoints = 0;
}
total = total + coursePoints;
}
return total;
}
const grades = [];
let noOfCourses = parseInt(prompt("Please enter # of courses taken: "));
console.log("\n")
for (let i = 0; i < noOfCourses; i++) {
grades.push(prompt('Enter grade recieved '));
}
console.log(calculateCP());
}
try to remove the return statement from the for loop and put it right after it..
change this:
return total = total + coursePoints;
to this:
... for loop
total = total + coursePoints;
}
return total;

Recursively setting a value depending on range using JavaScript

I don't know how to word this but this is what I'm trying to do:
if (score >= 0 && score <= 10) overallScore = 0;
else if (score >= 11 && score <= 20) overallScore = 1;
else if (score >= 21 && score <= 30) overallScore = 2;
else if (score >= 31 && score <= 40) overallScore = 3;
else if (score >= 91 && score <= 100) overallScore = 9;
...
Is there any way to recursively do this using a function?
overallScore = Math.max(0, Math.floor((score - 1) / 10));
no need for recursion. But if you need that:
const getOverall = score => score <= 10 ? 0 : getOverall(score - 10) + 1;
Recursion is not really appropriate here, since you can get the required value in constant time. Recursion becomes interesting when you need at least O(logn) time.
But as you ask for it, here is one way to make it recursive:
function range(score, depth = 0) {
return score <= 10 || depth >= 9 ? 0 : range(score-10, depth+1) + 1;
}
console.log(range(0)); // 0
console.log(range(10)); // 0
console.log(range(11)); // 1
console.log(range(60)); // 5
console.log(range(91)); // 9
console.log(range(110)); // 9

Error in JavaScript return code?

Here is the javascript code:
There is an error in code where nightSurcharges is added to total cost even if pickUptime is less than 20.
function TaxiFare() {
var baseFare = 2;
var costPerMile = 0.50;
var nightSurcharge = 0.50; // 8pm to 6am, every night //its flat 0.50 and not per mile
var milesTravelled = Number(document.getElementById("miles").value) || 0;
if ((milesTravelled < 1) || (milesTravelled > 200)) {
alert("You must enter 1 - 200 miles");
document.getElementById("miles").focus();
return false;
}
var pickupTime = Number(document.getElementById("putime").value) || 0;
if ((pickupTime == "") || (pickupTime < 0) || (pickupTime > 23)) {
alert("The time must be 0-23 hours");
document.getElementById("putime").focus();
return false;
}
var cost = baseFare + (costPerMile * milesTravelled);
// add the nightSurcharge to the cost if it is after
// 8pm or before 6am
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
alert("Your taxi fare is $" + cost.toFixed(2));
}
I want nightSurcharge to be added only when pickupTime is >=20, but that's not working right now.
Any help is appreciated. Thanks
This seems obvious to me.
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
This code right here adds nightSurcharge to the cost if pickupTime is greater than or equal to 20, OR less than 6. So of course it's added if it's less than 6.
if (pickupTime >= 20) {
cost += nightSurcharge;
}
Now it will only add to it if it's greater or equal to 20.
your code is:
if (pickupTime >= 20 || pickupTime < 6)
so if pickupTime is less then 6 it'll enter the if as well
http://jsfiddle.net/7rdzC/

Javascript looping error with arrays

I am trying to prompt the user for a weight smaller than 126. Then my javascript is supposed to classify the weight into a category. I have used arrays but every time I loop it writes the 3rd array, superfly class. What can I do to make it function properly?
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
var weight = parseInt(prompt("What is your weight?"), 10);
while (weight > 126) {
alert('Please enter a weight lighter than 126');
weight = parseInt(prompt("What is your weight?"), 10);
}
recruit();
function recruit() {
var weightClass = wArray[0];
if (0 < weight && weight < 112) {
weightClass = wArray[1];
} else if (112 < weight && weight < 115) {
weightClass = wArray[2];
} else if (weight > 115 && weight < 118) {
weightClass = wArray[3];
} else if (weight > 118 && weight < 122) {
weightClass = wArray[4];
} else if (weight > 122 && weight < 126) {
weightClass = wArray[5];
}
document.getElementById("weight").innerHTML = ('You are in ' + weightClass + ' class!');
}
Your first if condition is incorrect. You say if (112 < weight < 115). This first does 112 < weight, then takes the result of that and compares it to 115.
112 < weight evaluates to true or false; when used in numeric comparisons, true is 1 and false is 0. (Obviously) both 1 and 0 will always be less than 115, so this condition will always be true.
Also note that this script should be run onload of the page. This is because the div with the ID weight may not have loaded when the script executes and attempts to populate it. You can do this by saying:
<script type="text/javascript">
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
function calculateWeight() {
var weight = parseInt(prompt("What is your weight?"), 10);
while (weight > 126) {
alert('Please enter a weight lighter than 126');
weight = parseInt(prompt("What is your weight?"), 10);
}
recruit();
}
function recruit() {
var weightClass = wArray[0];
if (weight >= 112 && weight < 115) {
weightClass = wArray[1];
} else if (weight >= 115 && weight < 118) {
weightClass = wArray[2];
} else if (weight >= 118 && weight < 122) {
weightClass = wArray[3];
} else if (weight >= 122 && weight < 126) {
weightClass = wArray[4];
}
document.getElementById("weight").innerHTML = ('You are in ' + weightClass + ' class!');
}
</script>
<body onload="calculateWeight()">
<!-- include body contents here -->
</body>
the line:
if (112 < weight < 115) {
Should be
if (112 < weight && weight < 115) {

Categories

Resources