Javascript Taxi fare - javascript

I got the function setup and variables taken care. I am trying to calculate taxi fare per start zone, end zone and elapsed time.
Here what I have so far but it is not calculating well.
It keeps giving me $5
if( startZone == 1 && endZone == 1 ){
totalTaxiFare = baseCharge;
if( timeCovered > 0 && timeCovered <= 4 ){
baseCharge = 5.00;
charge = (0.75/timeCovered)*timeCovered;
totalTaxiFare = baseCharge + charge;
}
}
if( startZone == 1 && endZone == 2 ){
totalTaxiFare = baseCharge;
if( timeCovered > 4 && timeCovered <= 10 ){
baseCharge = 7.00;
charge =( 3.00 + (0.50 * ( timeCovered - 4 ) * ( 0.75 / timeCovered ) * timeCovered ) );
totalTaxiFare = baseCharge + charge;
}
}
document.writeln("<p> The total taxi fare is $" + totalTaxiFare + "</p>");

Ok, I don't know if I got the math correctly since I had to guess what the rates were by looking at the pattern. There's that zone thing I'm not sure what that's about, but by looking in the original code, I think it's a conditional to change the calculations for working 2 shifts?
Anyways, you should always use var for your variables, otherwise all of that data is floating around in globalspace. You had this expression: totalTaxiFare = baseCharge; floating around being exposed. So it looks as if ultimately your totalTaxiFare was constantly being changed to baseCharge which is at a constant value of 5.00. If you used var and kept the majority of your variables local, you'd probably get different results, but with the expressions you had those results wouldn't be accurate.
I'm definitely not a math wizard (lazy in high school), but is this an expression that would yield an appropriate result for cab fare?: `
(0.75/timeCovered)*timeCovered;
Ok, parenthesis first and we'll say 3 minutes? 3 hours? 3 time units I guess.
(.75/3)*3 which is (.25)*3 which is .75 so that was changed into a more appropriate expression:
(.75)*timeCovered;
So that would be
(.75)*3 = 2.25
Sorry if I sound harsh, I think that if you want to program, you should pay special attention to your math. Even if your syntax is flawless, it won't help if the math is even a little off.
Here's a DEMO, like I said before, I guessed as to how the expressions are done because you didn't provide the complete rates or given any details on time. It looks like it's working like it should give it a try. Good luck, sir ;-)

Related

How to create number suffixes such as "100K" without having to be repetitive?

I've been having a problem that when my auto clicker in my clicker game goes fast enough to get to 200 thousand, it starts to lag, and then it doesn't function properly, or as fast.
Is there a way to make 100 thousand turn into 100K, and 101 thousand turn into 101K without being repetitive?
I tried this with my original code, and realized putting up to 1000 suffixes into each function would be a little too hard:
if (number >= 100000) {
document.getElementById(ID).innerHTML = "100K"
}
if (number >= 101000) {
document.getElementById(ID).innerHTML = "101K"
}
and on and on.
I don't want multiple if statements!
This would work, but it would take up way too much space, and I know there is an easier way to it, but I just couldn't find it. Can anyone provide a way to do this?
Try separating the job of formatting your number into a different function.
SUFFIXES = 'KMBTqQsSOND' // or whatever you'd like them to be
function getSuffixedNumber(num) {
var power = Math.floor(Math.log10(num));
var index = Math.floor(power / 3);
num = Math.round(num / Math.pow(10, (index * 3))); // first 3 digits of the number
return num + (SUFFIXES[index - 1] || ''); // default to no suffix if we get an out of bounds index
}
You can call the function like this: var x = getSuffixedNumber(101000), the value of x will be "101K".

How to write and call functions in javascript with for loops?

I am working on writing code for a course and need to figure out why the code output is not executing properly. I am very new to coding, this is a beginner assignment so all help and explanations are greatly appreciated.
The output should look like this:
Output:
How many times to repeat? 2
Stats Solver execution 1 ====================
give a number 10.10203
give a number 20
give a number 30
give a number 40
give a number 50
sum: 150.10203
average: 30.020406
max: 50
min: 10.10203
ratio: 4.94
Stats Solver execution 2 ====================
give a number 3.21
give a number 2.1
give a number 1
give a number 5.4321
give a number 4.321
sum: 16.0631
average: 3.21262
max: 5.4321
min: 1
ratio: 5.43
done ====================
Here is the code:
"use strict";
function myMain() {
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
}
function wall(){
var num1 = Number(prompt("provide a number"));
var num2 = Number(prompt("provide a second number"));
var num3 = Number(prompt("provide a third number"));
var num4 = Number(prompt("provide a fourth number"));
var num5 = Number(prompt("provide a fifth number"));
var sum = (num1+num2+num3+num4+num5);
alert("sum: " + sum);
var avg = (sum/5);
alert("average: " + avg);
var max = (Math.max(num1,num2,num3,num4,num5));
alert("max: " + max);
var min = (Math.min(num1,num2,num3,num4,num5));
alert("min: " + min);
var ratio = (max/min);
alert("ratio: " + Math.floor(ratio*100)/100);
}
myMain();
Well you really aren't very far off at all. Actually your solution has all the code you need just some of it is in the wrong place. I would have posted this as a comment but as this is a new work account I can't actually post comments so here is a full solution with the explanations.
Your wall function, while annoying with all the alerts is actually correct and doesn't need any adjustments. With that said you might want to play with parseInt and parseFloat to make sure you are getting valid numbers but I am assuming that is outside of the scope of the assignment.
Now on to your main function.
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
This is ok and will prompt the user for a number, once again you might want to test that you got a valid number using the aforementioned links.
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This is where things start to fall apart a bit and where i think you are having problems. So I will break this down line for line and explain what each line is doing and you can compare that to what you think its doing.
var count = num;
Nothing crazy here, you are just creating another variable to hold the value in the num variable. Slightly redundant but not really a big deal.
for (var a=0; a<=num; a++) {count++;}
This is the line that appears to have given you the most confusion. This is the actual loop but inside the body of the loop { .... } nothing is being done except 1 is being added to count (count++). If I am understanding the assignment correctly, inside this loop is where you need to call your wall function after alerting the 'Stats Solver execution .....' stuff. All you need to do is move your function call inside this loop.
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This part is clearly you a little lost and just trying things to get it to work, don't worry even after 12+ years of development i still write code like this ;). You really don't need this as the actual call to wall() will work fine for you.
I am bored and am waiting on work so for the sake of being a complete answer here is an example of how your code should look. Please don't just hand this in rather try and actually understand the difference between what i wrote and what you did because these are some very basic concepts that if you gloss over will make your life much harder down the road. Always feel free to ask, thats how people learn.
function myMain(){
// get the number of repetitions from the user and cast as a number
var num = Number(prompt('Please enter the number of times to repeat'));
// loop from 0 to the number the user provided - 1 hence the <
for (var i = 0; i < num; i++){
// alert the iteration of the loop, you will notice i add 1 to num when we alert it; this is because it starts at 0 so the first time it displays it would show 'Stats Solver execution 0 ======' instead of 'Stats Solver execution 1 ======'
alert('Stats Solver execution ' + (num + 1) + ' ===============');
// call your wall function
wall();
// go back to the top of the loop
}
// alert that we are done.
alert('done===============')
}
// your wall function goes here
// call your myMain function to kick everything off
myMain();
Just for fun you might want to look at console.log instead of alert to not make it such an annoying process with all the popups.
If i missed anything or you are confused about anything don't hesitate to ask and i'll do my best to answer.

Var won't exceed billion

EDIT
I tested something out, and apparently, this:
if(info.max.value == "") {maxdesiredvalue = 999999999999999999999}
Returns in the chrome console:
> maxdesiredvalue
< 999999999
So I believe the problem really comes from there... is there a maximum number of digits we can attribute to a variable?
I'm into javascript for a few months now, and I've made a program that generates random weapons for a tabletop rpg.
Every weapon generated has a price relative to it's attributes. My problem today is that this price won't exceed 9 digits (cannot reach billion), even though it can.
In my generator, it is possible to choose certain properties before generating the weapon. If I intentionally try to generate something worth over a billion gold, it will crash instantly. On the other hand, if there is any way the weapon can be generated without exceeding the billion, it will do so.
For example, the most expansive metal is the "Residuum". The only 2 weapons that can be generated in Residuum are the dart and the shuriken, since they only use 1/16 of an Ingot. Therefore if I set the metal to be Residuum, they will be the only 2 possible generated weapons. From this point, if I try to specify I want a Residuum Sword, it will simply crash as explained earlier.
In my generation options, I also have a text input for the user to choose a minimum value and/or a maximum value for the weapon. I set the default max value to Infinity, so it should'nt be a problem.
function desiredvalue(){
if(info.max.value == "") {maxdesiredvalue = Infinity}
else {maxdesiredvalue = parseInt(info.max.value)}
if(info.min.value == "") {mindesiredvalue = 0}
else {mindesiredvalue = parseInt(info.min.value)}
}
In my html:
Min price: <input type="text" name="min" value="" onchange="desiredvalue()">
Max price: <input type="text" name="max" value="" onchange="desiredvalue()">
I already tried to deactivate this function to see if it was the problem, but even without a specific max value, weapons still won't be generated if their value exceeds 9 digits.
Maybe the problem sets inside the value formula, so here it is, even though it might not be a big help since it is all made up from variables.
WeapValue = ((((IngotValue * Ingots) + CraftTime + (actualEnchantTime * 3) + (LS * 0.02) + (R * 0.05) + BS + (FTH * 0.03)) * (((BPArace + BPAstatus + BPAlevel + ((BPAcrit1 + 1) * BPAcrit2)) / 100) + 1)) + PAenchant + PAaugment1 + PAaugment2 + PAaugment3)
Also the value is modified afterwards to fit in gold, silver or copper...
WeapValue.toLocaleString('en-US', {minimumFractionDigits: 0});
WeapValue = WeapValue.toFixed(2);
if (WeapValue >= 2) {WeapValue2 = Math.ceil(WeapValue); goldtype = " GP"}
else if (WeapValue < 2 && WeapValue >= 1) {WeapValue2 = WeapValue * 10; goldtype = " SP"}
else if (WeapValue < 1 && WeapValue >= 0) {WeapValue2 = WeapValue * 100; goldtype = " CP"}
Nothing else in the script really change the value, and all the variables affecting it are defined earlier, and I don't really think they are the problem, since they actually seem to work (they simply make the price exceed 9 digits).
If you have any questions related to the script, I'm here to answer, but I can't put the full script since it is very, very long (2543 lines)...
If anyone has an idea of how I can deal with my problem, it would be so appreciated! Again, I'm not a javascript expert, but I did my best and looked a lot on the Internet for help, but I still can't get rid of this problem...
Thank you!

Using exponents in Gravity Forms calculations

Firstly, I am by no means versed in JavaScript or jQuery. That being said, I'm using Gravity Forms to create a savings calculator that contains exponents. I found THIS thread, but am confused as to how it actually works in calculating an exponential value.
Here's my setup:
I have 3 user-defined fields:
Principal amount
Interest rate
Number of monthly payments
The actual calculations are hidden from the user. There are two formulas calculating at once here. The first is the 'User calculations' working to find a 'Total Interest'. The second is a 'Fixed calculations' with a fixed interest rate of 1.95%, instead of the user-defined field, working towards the same goal. The fixed rate aside, both formulas are identical, and the results of which are incorporated into a final formula free of exponents. Thankfully. Here are the first three 'Number' fields (name & formula) after the user input:
'CALC'<br>
( {Interest rate::2} / 12 ) / 100
'MP exponent'
( 1 + {CALC:8} ) <---This is the formula that requires an exponent equal to the user-defined "Number of monthly payments" field.
'MP numerator'
{CALC:8} * {Principal amount::1} * {MP exponent:10}
The formula goes on and incorporates the MP exponent field multiple times. Given my case here, can I even use the aforementioned script (unedited from its source post):
<script>
gform.addFilter( 'gform_calculation_result', function(result, formulaField, formId, calcObj ){
if ( formulaField.field_id == "2" ) {
var field_five = jQuery('#input_2_5').val();
result = field_five * 12;
}
return result;
});
</script>
...for my calculation? I'm not at all sure how to specify something like this in 4 separate fields... I understand this may not be possible with Gravity Forms - or certainly not simple - so I greatly appreciate any help the community may offer me.
The javascript snippet you used above will change what the user sees, but it will not change the saved form data, per say. You instead need to add a PHP filter to the functions.php file of your theme.
add_filter( 'gform_calculation_result', function ( $result, $formula, $field, $form, $entry ) {
if ( $form['id'] == 1 && $field['id'] == 10 ) {
$base = 1 + (float) rgar( $entry, '8' ); // '8' should be field ID of Calc
$exponent = (float) rgar( $entry, '1' ); // '1' should be field ID of Number of monthly payments
$result = pow( $base, $exponent );
}
return $result;
}, 10, 5 );
One warning: this will not change anything that the user "sees" when filling out the form. It will only change the final calculation after the user hits the submit button.
It would also be cleaner to do all of your calculations in a filter like this rather than using hidden form data.

Javascript value set null if value equals nothing

Right now I am working on a timesheet where users can set their in time, their out time, and how long they've been at lunch. Then I use a function that subtracts the in time & the lunch from their out time to figure out their hours, plus possible overtime. What I want is to have javascript set the value of the overtime field to '' (aka null) if the amount of time they were at work is 8 hours or less.
My code for checking overtime is this:
// Return difference between two times in hh:mm[am/pm] format as hh:mm
function checkOvertime(timein, timeout, away) {
// Small helper function to pad single digits
function z(n){return (n<10?'0':'') + n;}
// Get difference in minutes
var subtotal = daytimeStringToMins(timeout) - daytimeStringToMins(timein) - timeStringToMins(away);
var regularhours = '08:00';
if (subtotal > timeStringToMins(regularhours)) {var overtime = daytimeStringToMins(timeout) - daytimeStringToMins(timein) - timeStringToMins(away) - timeStringToMins(regularhours);}
else {var overtime = '0';}
return z(overtime/60 | 0) + ':' + z(overtime % 60);
}
and then in my calculation function I have this:
if (checkOvertime(timein, timeout, away).value == '00:00') {
document.getElementById("date-1-overtime").value = '';
} else {
document.getElementById("date-1-overtime").value = checkOvertime(timein, timeout, away);
}
So if a person is at work for 8 hours, then the "date-1-overtime" field says "00:00" but I would like it to put nothing in there so the sheet prints out more cleanly.
I think maybe I am confusing the difference between strings and integers in the calculation functions but I'm not sure, hopefully someone could help me!
I think you should change this method to use regular expressions to extract the appropriate parts of the input and then use parseint to get the value in a numeric form.
Convert that to minutes and if the minutes are less than or equal to 480 (8 * 60), return the actual string.
Also, you can't really assign a null value to an html param. null is not the same as 0. null is essentially, undefined.
You should return the number of minutes worked overtime from your function and use 0 for overtime if the user didn't work overtime.

Categories

Resources