Javascript Save Max Value of Loop Variable - javascript

I have a variable that is updated every 2 seconds with a new value ( speed ) , I want to keep saved the highest value .
How can I do?
snipper
var velocità = spazio / t1; // km/h
console.log('Stai andando a: ' + velocità);
document.getElementById("velocità").innerHTML = velocità;

var max = 0;
...
...
if(velocità > max)
max = velocità;

Related

JavaScript Variables adds themselves and stacks up

So when I want to calculate variable1 + variable2 * variable3 it only add themselves and stacks up.
Code:
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function func() {
var pxL = localStorage["pxL"];
var val = document.getElementById("bp").innerHTML;
document.getElementById("bp").innerHTML = funcCalc(val, randomRange(1, 10), pxL);
}
function funcCalc(val, random, px) {
return val + random * px;
}
The thing is that in HTML document there is element which indicates the variable, and the variable would add itself + random and multiply by third variable on button click. The problem is that the variables calculate themselves and instead of changing the innerHTML, they adds it to innerHTML.
HTML:
<stat id="bpT">BPT: <textarea class="statIndic" id="bp" disabled>0</textarea></stat>
I want output like 15 and not 015 etc.
You need to get an integer, not a string:
var pxL = parseFloat(localStorage["pxL"]);
var val = parseFloat(document.getElementById("bp").innerHTML);
document.getElementById("bp").innerHTML = funcCalc(val, randomRange(1, 10), pxL);
.innerHTML returns a string for sure. Depending on how you store the variable, localStorage might return a string or number.
You can also use Number():
var pxL = Number(localStorage["pxL"]);
var val = Number(document.getElementById("bp").innerHTML);

Javascript/Jquery: Compute the values based on the values or null values of input type

I am new to Javascript/Jquery. Below is my code that can compute an average (A) value as long as there are 3 present values in the input.
Here is the jquery code
$(".q-value, .e-value, .t-value").click(function(){
let currentRow = $(this).closest('tr');
let EValue = parseFloat(currentRow.find('.e-value').val());
let QValue = parseFloat(currentRow.find('.q-value').val());
let TValue = parseFloat(currentRow.find('.t-value').val());
currentRow.find('.a-value-core').val((EValue + QValue + TValue ) / 3);
currentRow.find('.a-value-support').val((EValue + QValue + TValue ) / 3);
currentRow.find('.a-value-research').val((EValue + QValue + TValue ) / 3);});
I would like to set an average value even if the Q or E or T input is null However, A value is not computing. when Q or E or T value is null.
For example.
Q = 5, E = null and T = null then A value should be 5
Q = 5, E = 2 and T = null then A value should be 3.5
Q = 5, E = 5 and T = 5 then A value should be 5
try
Number(currentRow.find('.*-value').val());
instead of
parseFloat(currentRow.find('.*-value').val());
as when no value is selected in the dropdown, .val() returns an empty string, not null, and parseFloat("") returns NaN. When you try to add NaN to any number answer returned is still a NaN and your result field stays empty.
Few more notes:
What type of elements are .a-value-**** ? They need to be textfields or such to use .val(). If not, use .text()
Your formula to calculate average of only available numbers will not work when you divide by 3, irrespective of the input. You need to change the logic there as well.
I would use .change instead of .click for a dropdown
PS: It's always a good idea to use console.log(variable) for quick debugging and look for error messages in the console inside the Devtools of the browser and share the same with your question
Hello #AlwaysaLearner noted on your notes. as for the computations, I have to change the logic for the computation by creating a counter for Q, E or T value !== 0 then counter + 1 inside an if else statement. below is the code
//COMPUTE THE AVERAGE PER ROW
$(".q-value, .e-value, .t-value").change(function(){
let currentRow = $(this).closest('tr');
let EValue = Number(currentRow.find('.e-value').val());
let QValue = Number(currentRow.find('.q-value').val());
let TValue = Number(currentRow.find('.t-value').val());
let counter = 0
if (QValue !== 0){
counter = counter + 1
}
if (EValue !== 0){
counter = counter + 1
}
if (TValue !== 0){
counter = counter + 1
}
currentRow.find('.clerical-value-core').val((EValue + QValue + TValue ) / Number(counter));
currentRow.find('.technical-value-core').val((EValue + QValue + TValue ) / Number(counter));
currentRow.find('.a-value-support').val((EValue + QValue + TValue ) / Number(counter)); });
and now It works perfectly. I also change the handler .change and also applied Number function for each field.

How to use the various rampToValueAtTime methods

When I use the following code to fade in a file it doesn't work as I expect. I expect a gradual fade in from 0 to 1 over the course of 5 seconds, instead I get an abrupt change five seconds into playing the file where the gain instantly goes from 0 to 1. What am I not understanding ?
soundObj.play = function() {
playSound.buffer = soundObj.soundToPlay;
playSound.connect(gainNode);
gainNode.gain.value = 0;
gainNode.gain.exponentialRampToValueAtTime(1, audioContext.currentTime + 5);
gainNode.connect(audioContext.destination);
playSound.start(audioContext.currentTime);
}
Update/Edit
I changed the above code to the following and it seems to work, now I am researching why. I've added a few comments. Mainly inquiring as to if adding a setValueAtTime method is necessary and if a non zero value is necessary for the gain.value properties default value.
soundObj.play = function() {
playSound.buffer = soundObj.soundToPlay;
playSound.connect(gainNode);
gainNode.gain.value = 0.001; // If set to 0 it doesn't fade in
gainNode.gain.setValueAtTime(gainNode.gain.value, audioContext.currentTime); // Is this needed to have the other RampToValue methods work ?
gainNode.gain.exponentialRampToValueAtTime(1, audioContext.currentTime + 7);
gainNode.connect(audioContext.destination);
playSound.start(audioContext.currentTime);
}
A non-zero positive value is necessary for exponentialRampToValueAtTime. This isn't a Web Audio thing as much as it's just a math thing.
There's really no way to exponentially grow a value of 0.
Here's a rough version of the algorithm Chrome uses (rewritten in JS):
// start value
var value1 = 0.1;
// target value
var value2 = 1;
// start time (in seconds)
var time1 = 0;
// end time (in seconds)
var time2 = 2;
// duration
var deltaTime = time2 - time1;
// AudioContext sample rate
var sampleRate = 44100;
// total number of samples
var numSampleFrames = deltaTime * sampleRate;
// time incrementer
var sampleFrameTimeIncr = 1 / sampleRate;
// current time (in seconds)
var currentTime = 0;
// per-sample multiplier
var multiplier = Math.pow( value2 / value1, 1 / numSampleFrames );
// output gain values
var values = new Array( numSampleFrames );
// set up first value
var value = value1 * Math.pow( value2 / value1, ( ( currentTime - time1 ) * sampleRate ) / numSampleFrames );
for ( var i = 0; i < numSampleFrames; ++i ) {
values[ i ] = value;
value *= multiplier;
currentTime += sampleFrameTimeIncr;
}
If you change value1 to zero, you'll see that the output array is basically full of NaN. But Chrome also adds a bit of extra code to save you from that by special-casing instances where your value is <= 0 so that you don't actually end up with gain values of NaN.
If none of that makes sense, let me put it this way. In order to exponentially grow a value, you basically need a loop that looks like this:
for ( var i = 0; i < length; ++i ) {
values[ i ] = value;
value *= multiplier;
}
But if your initial value is 0, well, 0 multiplied by any other number is always 0.
Oh, and if you're interested (and can read C++), here's a link to the code that Chrome uses: https://chromium.googlesource.com/chromium/blink/+/master/Source/modules/webaudio/AudioParamTimeline.cpp
Relevant stuff is on line 316.
Edit
Apologies for a Chrome-centric explanation. But the underlying math concept of not being able to exponentially grow a value of zero will hold with any implementation.

How to add a value randomly to an array using JavaScript

I am new to JavaScript and i am going through a task where i have to randomly disperse an input value between 12 loads. The other side is that each element of the array cannot differ from the next by more than one.
so for example if i have an amount of 30 i need to distribute this amount between 12 camels. I have so far written the code below, but i am using TextPad as requested i am not sure how to print out the result on the same line.
var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0]
var div = amount/12;
var mod = amount%12;
var x = mod / 12;
for(i=0;i<camels.length;i++){
WScript.echo(camels[i] + "|" + Math.floor(div) + "|" + mod + "|" + x)
}
please comment if you need anymore info , Thanks
Here's my take on it. Note that for the requirement that states that the array values cannot differ from the next one by more than one, I consider the array to be looping, i.e. the value after the last value is the first value again.
var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];
while (amount > 0) {
var index = Math.floor(Math.random() * camels.length);
var previous = (camels.length + index - 1) % camels.length;
var next = (index + 1) % camels.length;
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {
camels[index]++;
amount--;
}
}
Update
As requested by the OP, here's an annotated version:
// the amount that needs to be distributed among the camels
var amount = 30;
// the actual values for all 12 camels, initially all zero
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];
// as long as we have something to distribute
while (amount > 0) {
// get a random current index in the array, i.e. a value between 0 and 11
var index = Math.floor(Math.random() * camels.length);
// calculate the index previous to the current index;
// in case the current index is 0, the previous index will be 11
var previous = (camels.length + index - 1) % camels.length;
// calculate the index next to the current index;
// in case the current index is 11, the next index will be 0
var next = (index + 1) % camels.length;
// if adding 1 to the camel at the current index makes it so that
// the difference with the camel at the previous index is 1 or lower
// the difference with the camel at the next index is 1 or lower
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {
// go ahead and add 1 to that camel
camels[index]++;
// and decrement the amount accordingly
amount--;
}
}
By adding an outer cycle you can correctly add the remaining part of the amount.
while(amount > 0){
//add amount to camels
}
Check if this Fiddle is what you want to achieve.

I have a field calculating and need to display a minimum if the result is below 60

Sorry this is obviously my first time here, I am just learning how to work in javascript. My question is this: I have some basic calculations determing a price of a service for our non-profit. t is the number of rooms * 0.81. But we have a monthly minimum of $60. So I need to know how I would factor that into the pricing function. I know it goes that "if x < 60, then 60", just not sure how the language would be written. I will include the full js.
var listenerFieldIDs = {"roomCountID":"item4_text_1"}; //Currently the only form we are using for room count has this value set as its ID attribute.
var impactFields = ["item12_text_1","item1_text_1","item16_text_1","item18_text_1","item20_text_1"]; //Field IDs for the form that will be changed constantly.
var estimatedBottleSize = 1.5, occupancyRate = (60 / 100), collectionDuration = 365, soapOuncesRecoverable = 0.63, bottleOuncesRecoverable = 0.47,lbConversion = 0.0626, rate = 0.81;
var $ = function(id){ //Shortcut to save some typing. Instead of having to write out document.getElementById(elementID) every time I need to access an element, I can put $(elementID).property or $(elementID).method() I need more easily.
return document.getElementById(id);
}
var updateFormField = function(id,amount){ //Updates a form field when gives the element ID and the amount.
$(id).value = amount;
}
var updateForm = function(roomCount){
// This is called when all form data needs to be updated. This is generally invoked each time a keystroke in the room count field.
updateFormField(impactFields[0],calculateLbsOfSoap(roomCount).toFixed(2)); //Updating the first form field after calculating the total weight of soap in lbs.
updateFormField(impactFields[1],calculateLbsOfBottles(roomCount).toFixed(2)); //Same thing as above, but bottles/amenities.
updateFormField(impactFields[2],calculateBarsOfSoap(roomCount).toFixed(0)); //Updating the third form field after calculating the total number of distributed units.
updateFormField(impactFields[3],calculateBottles(roomCount).toFixed(0)); //Same as above, but bottles/amenities.
updateFormField(impactFields[4],("$" + calculatePrice(roomCount).toFixed(2))); //Updating price.
}
var listenForNumbers = function(event){ //This function is acting as a handler for when anything is entered into the field.
updateForm($(listenerFieldIDs["roomCountID"]).value);
}
var calculateLbsOfSoap = function (rmCnt){ // Calculate the weight of soap and return the amount.
return checkCount(rmCnt) ? 0 : ((soapOuncesRecoverable * lbConversion) * (rmCnt * occupancyRate) * collectionDuration);
}
var calculateLbsOfBottles = function (rmCnt){ // Calculate the weight of bottled amenities and return the amount.
return checkCount(rmCnt) ? 0 : ((bottleOuncesRecoverable * lbConversion) * (rmCnt * occupancyRate) * collectionDuration);
}
var calculateBarsOfSoap = function(rmCnt){ // Calculate how many bars are distributed if the room count is not 0.
return checkCount(rmCnt) ? 0 : ((calculateLbsOfSoap(rmCnt) * 16) / 3);
}
var calculateBottles = function(rmCnt){ // Calculate how many bottles are distributed if the room count is not 0.
return checkCount(rmCnt) ? 0 : (((calculateLbsOfBottles(rmCnt) * 16) / estimatedBottleSize) * (2 / 3));
}
var calculatePrice = function(rmCnt){
return checkCount(rmCnt) ? 0 : (rmCnt * rate);
}
var checkCount = function(count){ //If the count is 0 or less than 0, the number is useless so just return 0 to prevent odd results.
return (count < 0 || count == 0) ? true : false;
}
var initializeRealTimeCalcToForm = function(){
if(window.attachEvent){
$(listenerFieldIDs["roomCountID"]).attachEvent("onkeydown",listenForNumbers,false);
$(listenerFieldIDs["roomCountID"]).attachEvent("onkeyup",listenForNumbers,false);
$(listenerFieldIDs["roomCountID"]).attachEvent("onkeypress",listenForNumbers,false);
$(listenerFieldIDs["roomCountID"]).attachEvent("onchange",listenForNumbers,false);
} else{
//But if NOT IE... :-D
$(listenerFieldIDs["roomCountID"]).addEventListener("keydown",listenForNumbers,false);
$(listenerFieldIDs["roomCountID"]).addEventListener("keyup",listenForNumbers,false);
$(listenerFieldIDs["roomCountID"]).addEventListener("keypress",listenForNumbers,false);
$(listenerFieldIDs["roomCountID"]).addEventListener("change",listenForNumbers,false);
}
}
window.onload = function(){
initializeRealTimeCalcToForm();
}
If you only want to set a minimum value of 60 to the variable myvar, you can do
myvar=Math.max(60,myvar);
Edit:
Then, if you want the value returned by calculatePrice to be at least 60, use:
var calculatePrice=function(rmCnt){
return Math.max(60,checkCount(rmCnt) ? 0 : (rmCnt * rate));
}
Note 1:
Do you know that you can declare functions like this?
function calculatePrice(rmCnt){
return Math.max(60,checkCount(rmCnt) ? 0 : (rmCnt * rate));
}
It's shorter and this way you can call the function before declaring it!
Note 2:
If you want that value to be at least 60, I don't understand the following code:
checkCount(rmCnt) ? 0
Why 0?

Categories