Error in JavaScript return code? - javascript

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/

Related

Simplifying multiple similar If statements (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;
}

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

How do you return a value if it exceeds a certain number?

I am making a app for a board game for school, the game is based on Game of the Goose. In this game once you are on a certain spot and you exceed the highest number it sets you back the value that is left. For example, if you are at 64 and you roll 4 you return to spot 66 because 67 is the highest number. I'm using a math.random and a math.floor to add a number to the player from 1 to 6.
*edit:
Here is the code i am writing, it's a bit sloppy though, sorry for that.
var players = [
{
name: "Speler 1",
positie: 0
},
{
name: "Speler 2",
positie: 0
},
{
name: "Speler 3",
positie: 0
},
{
name: "Speler 4",
positie: 0
}
];
var position = 0;
var currentPlayer = players[position];
function rolClick(){
if (position >= players.length){
position = 0;
};
currentPlayer = players[position++];
var rollen = Math.floor(Math.random() * 6) + 1;
if (rollen === 1){
currentPlayer.positie += 1;
}else if(rollen === 2){
currentPlayer.positie += 2;
}else if(rollen === 3){
currentPlayer.positie += 3;
}else if(rollen === 4){
currentPlayer.positie += 4;
}else if(rollen === 5){
currentPlayer.positie += 5;
}else if(rollen === 6){
currentPlayer.positie += 6;
}};
Suppose the variable that you are increasing is called current.
function getRandomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var highest = 67;
current += getRandomBetween(1, 6);
if(current > highest) return highest-1;
Something like this..
function onRoll(this) {
currentVal=this.value;
x=Math.random();//Ensure you have your limitations of random number in place;
newVal=currentVal+x;
if(newVal>66)//whatever your limit
return 66;
else
return newVal;
}
This script do what you want (I think):
maxValue = 67
dice = Math.floor((Math.random() * 10) + 1)
oldValue = 64
if(oldValue + dice > maxValue){
alert("You reached the maximum. Your Value is set to " + (maxValue-1))
newValue = maxValue-1
}else{
newValue = oldValue+dice
}
You should read the if Statements...
here you can read and learn it:
http://www.w3schools.com/js/js_if_else.asp

Calculating unit price based on quantity entered

I'm trying to create a script that displays a price in one box based on the number of employees entered in an adjacent box.
The script works fine for a static amount, i.e. the base price is £8 per employee. If 5 is entered the price displayed is correct, £40.
The problem I'm having is changing the unit price when a certain threshold is met. The unit price for 1-5 employees is 8, 6-21 is 7 and 22-50 is 6.
No matter what is entered in the employee box, the number is always multiplied by 8.
I'm very inexperienced when it comes to javascript so any help will be very welcome!
Here is my code:
<div class="employee-button">
<form name="calculator" id="calculator">
<input name="employees" id="employees" type="text" placeholder="# of Employees" />
</form>
</div>
<div class="cost-button">
<span id="result">Monthly Cost</span>
</div>
Javascript
$(function() {
var ccNum;
$('#employees').keyup(function(){
ccNum = $(this).val();
});
if((ccNum >= 0) && (ccNum <= 5)){
var unitPrice = 8
}
else if((ccNum >= 6) && (ccNum <= 21)){
var unitPrice = 7
}
else if((ccNum >= 21) && (ccNum <= 50)){
var unitPrice = 6
}
else var unitPrice = 8;
$('#employees').keyup(function(){
$('#result').text(ccNum * unitPrice);
});
})
Put everything within the keyup function. Your code wasn't working because the logic to calculate the price is only executed once, not for every keyup event.
$('#employees').keyup(function(){
var ccNum = $(this).val();
if((ccNum >= 0) && (ccNum <= 5)){
var unitPrice = 8
}
else if((ccNum >= 6) && (ccNum <= 21)){
var unitPrice = 7
}
else if((ccNum >= 21) && (ccNum <= 50)){
var unitPrice = 6
}
else var unitPrice = 8;
$('#result').text(ccNum * unitPrice);
});
In addition to putting the code inside your event handler, you do not need to keep declaring the same variable over and over. Also the test for 0 to 5 is not needed (as already covered by the default value):
$('#employees').keyup(function(){
var ccNum = ~~$(this).val();
// Start with the default
var unitPrice = 8;
if((ccNum >= 6) && (ccNum <= 21)){
unitPrice = 7;
}
else if((ccNum >= 21) && (ccNum <= 50)){
unitPrice = 6;
}
$('#result').text(ccNum * unitPrice);
});
Note: ~~ is a shortcut conversion to an integer value.

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