JQuery Mobile Javascript Complex Equation - javascript

I am in need of some help.
I have a stupidly complex piece of math that I need to turn into a javascript equation and it's not working (annoyingly!!).
Basically the sum is:
No#1 / No#2 = Result1
Result1 - 1 = Result2
Result2 * 100 = Result3
Result3 rounds up or down - display result.
I hope that makes sense.
The code I am using is:
var rc1TyreRatio2 = Number(Apperyio("rc1TyreRatio2").val());
var rc1Test1 = Number(Apperyio("rc1Test1").val());
var rc1Test2 = Number(Apperyio("rc1Test2").val());
var rc1Test1 = rc1InterAxle / rc1TyreRatio2;
var rc1Test2 = rc1Test - 1;
var rc1Lead = rc2Test * 100;
Apperyio('rc1Lead').val(rc1Lead.toFixed(2) + "%");
The components are standing JQuery Mobile 'textareas' & they are: rc1TyreRatio2 | rc1Test1 | rc1Test2 | rc1Lead.
I know it's in the appery.io platform, it wasn't my first choice, but my client's as they have other stuff hosted there, so I have to work with it, it use's JQM JavaScript just fine,
Any idea's how I can get this working? using just JavaScript and no HTML at all.
Thank you all,
- Tech-Xcellent

Use brackets to do certain calculations that are unique to get a result. You can chain as many brackets with calculations as you want.
i.e
(calculation A = result) * (calculation B = result) / (calculation C = result) + (calculation D = result)
Example
var noa = 20;
var nob = 10;
var Total = (noa / nob - 1) * 100;
alert (Math.round(Total))
Result is 100
if i dint use brackets e.g var Total = noa / nob - 1 * 100; the result would show -98 which is wrong
Demo

Related

Pure Javascript, Cannot assign variables to an array

I am still learning JS (not jquery). So in learning, I am starting with a simple game. I found a problem. I cannot get these arrays to work, as they are producing a NaN.
var clickMultiplier = 1.11;
var idleMultiplier = 1.15;
var idleBuffsCost = [];
idleBuffsCost[0] = 100;
var clickBuffsCost = [];
clickBuffsCost[0] = 100;
var trainerBuffsCost = [];
trainerBuffsCost[0] = 1250;
for (i = 1; i <= 20; i++) {
var j = i - 1;
idleBuffsCost[i] += idleBuffsCost[j] * idleMultiplier;
clickBuffsCost[i] = clickBuffsCost[i] + clickBuffsCost[j] * clickMultiplier;
trainerBuffsCost[i] += trainerBuffsCost[j] * 1.25;
}
console.log(clickBuffsCost[0]); // works = 100
console.log(clickBuffsCost[1]); // does not work NaN
What am I doing wrong?
Also, I am used to doing arrays (like the above) as
... idleBuffsCost[i-1]
However, that does not seem to be working.
What do you think? Am I not seeing the forest for the trees (I normally program in php/mysql/pascal/qb64(and other derivations) and a few more languages - just adding JS to the list hahaha)
ps the different assignments are because I was trying different logic operations.
thanks to a few people here - I made a simple mistake. the loop was trying to assign a value to an index that was not assigned yet. Here is the fix - I removed the += and left just =
idleBuffsCost[i] = idleBuffsCost[j] * idleMultiplier;
clickBuffsCost[i] = clickBuffsCost[j] * clickMultiplier;
trainerBuffsCost[i] = trainerBuffsCost[j] * 1.25;
special thanks to: #certainPeformance, #Wais Kamal and #David I wish I could green check them all. But they were helpful none-the-less, Thanks guys!
There is a little mistake in your code. Search this line of code.
clickBuffsCost[i] = clickBuffsCost[i] + (clickBuffsCost[j] * clickMultiplier);
change to:
clickBuffsCost[i] = clickBuffsCost[j] + (clickBuffsCost[j] * clickMultiplier); // notice the difference after the = part
Since i will start at 1, clickBuffsCost[1] is undefined because clickBuffsCost only consists of one item at the beginning.
Here is where you've gone wrong:
for (i = 1; i <= 20; i++) {
var j = i - 1;
idleBuffsCost[i] += idleBuffsCost[j] * idleMultiplier;
clickBuffsCost[i] = clickBuffsCost[i] + (clickBuffsCost[j] * clickMultiplier);
trainerBuffsCost[i] += trainerBuffsCost[j] * 1.25;
}
First of all, define i before using it. Defining variables is good programming practice.
clickBuffsCost[i] = clickBuffsCost[i] + (clickBuffsCost[j] * clickMultiplier);
In the first iteration of your loop, i has the value 1, while j has the value 0. You are setting the second element of clickBuffsCost as clickBuffsCost[i] + (clickBuffsCost[j] * clickMultiplier). clickBuffsCost[i] (which is equal to clickBuffsCost[1] in this case) is undefined, which is why you are getting NaN when calling console.log(clickBuffsCost[0]).
You need to initialise your array lengths. For example, if you know you have 20 elements in an array, you should initialise an array as follows:
const testArr = new Array(20);.
Alternatively, if you don't know the length of your array, instead of indexing the ith element of the array and assigning it a value, you could use the array push(..) function. This method means you do not have to initialise an array with a length.
You can read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Loop through jQuery arrays / Output values to a div

I have a button that dynamically creates 2 inputs per click
Data of Input 1: string
Data of Input 2: number (float) (0-100)
I am creating an array of each like this.
var recipe_flavour_name = $("input[name='flav-name']").map(function() {return $(this).val();}).get();
var recipe_flavour_percent = $("input[name='flav-percent']").map(function(){return $(this).val();}).get();
As far as I can tell, the arrays are comma separated values.
Let's for simplicity's sake say:
recipe_flavour_name = a,b,c
recipe_flavour_percent = 5,6,7
I then want to take the number value to use in a function and then loop through all the values and use jQuery's .html() to add the values to a div.
I have tried this: flavPercent1 is just recipe_flavour_percent
var arrayLength = flavPercent1.Length;
for (var i = 0; i < arrayLength; i++) {
var flavML = (flavPercent1[0] / 100 * 100 * 1000) / 1000;
var flavGrams = (flavML * .98 * 100) / 100;
var flavPercent = (flavML / 100 * 1E4) / 100;
$('.live-flavours').html('<tr>'+flavName[0]+'<td></td>'+parseFloat(flavML).toFixed(2)+'<td>'+parseFloat(flavGrams).toFixed(2)+'</td><td>'+parseFloat(flavPercent1[0]).toFixed(2)+'</td></tr>');
};
But I only get flavGrams and flavPercent returned, dynamically adding more data to the array does nothing.
What do I want to achieve?
Grab the values of specified inputs in an array.
Pass them to a function.
Loop through the values and output them in HTML using jQuery.
I hope that makes sense and thanks in advance.
Ok, so assuming that you don't have a problem getting the arrays you need, the problem lies within your for loop.
YOUR CODE:
for (var i = 0; i < arrayLength; i++) {
var flavML = (flavPercent1[0] / 100 * AMOUNT * 1000) / 1000;
var flavGrams = (flavML * .98 * 100) / 100;
var flavPercent = (flavML / AMOUNT * 1E4) / 100;
$('.live-flavours').html('<tr>'+flavName[0]+'<td></td>'+parseFloat(flavML).toFixed(2)+'<td>'+parseFloat(flavGrams).toFixed(2)+'</td><td>'+parseFloat(flavPercent1[0]).toFixed(2)+'</td></tr>');};
You put everything in the for loop, yet make no reference to the index. I'm assuming everywhere you put [0] you actually want [i]. This means that every time the index increases, you are getting the next array element.
You should use .append instead of .html. .html means that the current html will be replaced by what you are adding.
Finally, although making it dynamic is possible, I'm not sure that JQuery is the best libary to use in this case. I'd suggest taking a look at libraries such as Vue or MoonJs (both are very light and very simple libraries) etc... to find a much easier, and frankly better way to do this. They allow for dynamic rendering, and what you are trying to do becomes insanely simplified.
Hope this helps.
(hopefully) WORKING CODE:
for (var i = 0; i < arrayLength; i++) {
var flavML = (flavPercent1[i] / 100 * AMOUNT * 1000) / 1000;
var flavGrams = (flavML * .98 * 100) / 100;
var flavPercent = (flavML / AMOUNT * 1E4) / 100;
$('.live-flavours').append('<tr>'+flavName[i]+'<td></td>'+parseFloat(flavML).toFixed(2)+'<td>'+parseFloat(flavGrams).toFixed(2)+'</td><td>'+parseFloat(flavPercent1[i]).toFixed(2)+'</td></tr>');};

d3 how to turn a set of numbers into a larger set representative of the first set

Say I have array [1,2,5,18,17,8] and I want to turn that into an array of length 40 that follows the same path.
a = [1,2,5,18,17,8];
stepSize = 1 / (40 / a.length);
then i think i could do something like
steps = [];
for( var i = 0; i < 1; i+= stepSize) {
steps.push(d3.interpolate(a[0],a[1])(i));
}
and then repeat that for all the elements. My question is there a better way to do this?
I can only guess what your real problem is but I think you want to plot these values and have a smooth curve. In that case use line.interpolate() https://github.com/mbostock/d3/wiki/SVG-Shapes#line_interpolate
In case you DO know what you need and your solution works for you, take this tip:
Never iterate over stepSize. Calculate it once and multiply it with i in every loop where i goes from 0 to 40. This way you work around precision problems.
Your algorithm cleaned up, tested and working:
var a = [1,5,12,76,1,2];
var steps = 24;
var ss = (a.length-1) / (steps-1);
var result = new Array(steps);
for (var i=0; i<steps; i++) {
var progress = ss * i;
var left = Math.floor(progress);
var right = Math.ceil(progress);
var factor = progress - left;
result[i] = (1 - factor) * a[left] + (factor) * a[right];
// alternative that actually works the same:
//result[i] = d3.interpolateNumber(a[left], a[right], factor);
}
console.log(result);

JavaScript issue in IE when adding numbers

I have a simple form, with 5 textboxes and 3 answers (also textboxes). The form calculates a result for the user with number inputs. My problem is my calculation does not work in IE, but works fine in both Chrome and Firefox.
What's wrong?
Here is my function:
function addNumbers()
{
var val1 = Number(document.getElementById("value1").value);
var val2 = Number(document.getElementById("value2").value);
var val3 = Number(document.getElementById("value3").value);
var val4 = Number(document.getElementById("value4").value);
var val5 = Number(document.getElementById("value5").value);
var val6 = '100';
var ansD1 = document.getElementById("answer1");
ansD1.value = Number((val1 * val2) * (val4 / val6));
var ansD2 = document.getElementById("answer2");
ansD2.value = Number((val1 * val3) * (val5 / val6));
var ansD3 = document.getElementById("answer3");
ansD3.value = Number (ansD1.value - ansD2.value);
}
Change this line:
var val6 = '100';
to this:
var val6 = 100;
You want all your values to be actual numbers (not strings) so you can do math on them.
Also, you don't need the Number() in these lines because the result of the numeric math is already a number. Plus the assignment to the answer fields is just going to convert the result to a string anyway:
ansD1.value = Number((val1 * val2)*(val4/val6));
They can just be this:
ansD1.value = (val1 * val2)*(val4/val6);
The modified code works fine in IE here: http://jsfiddle.net/jfriend00/5WFRA/.
Instead of Number use parseInt, otherwise they are treated as strings

How to translate this bit of Python to idiomatic Javascript

My code so far:
// The q constant of the Glicko system.
var q = Math.log(10) / 400;
function Player(rating, rd) {
this.rating = rating || 1500;
this.rd = rd || 200;
}
Player.prototype.preRatingRD = function(this, t, c) {
// Set default values of t and c
this.t = t || 1;
this.c = c || 63.2;
// Calculate the new rating deviation
this.rd = Math.sqrt(Math.pow(this.rd, 2) + (Math.pow(c, 2) * t));
// Ensure RD doesn't rise above that of an unrated player
this.rd = Math.min(this.rd, 350);
// Ensure RD doesn't drop too low so that rating can still change
// appreciably
this.rd = Math.max(this.rd, 30);
};
Player.prototype.g = function(this, rd) {
return 1 / Math.sqrt(1 + 3 * Math.pow(q, 2) * Math.pow(rd, 2) / Math.pow(Math.PI, 2));
};
Player.prototype.e = function(this, p2rating, p2rd) {
return 1 / (1 + Math.pow(10, (-1 * this.g(p2rd) * (this.rating - p2rating) / 400)));
};
I'm working on a JS/HTML implementation of the Glicko rating system and am heavily borrowing from pyglicko -- which is to say, completely ripping it off.
It's rather short (probably less than 100 LoC without comments) but I'm having my misgivings about whether my translation will work because honestly, I have no idea how Javascript scoping and this actually work. You can see what I have at the link at the top.
But in specific I'm wondering how you would express this bit of Python code in Javascript. Basically _d2 is inside a class definition for Player.
def _d2(self, rating_list, RD_list):
tempSum = 0
for i in range(len(rating_list)):
tempE = self._E(rating_list[i], RD_list[i])
tempSum += math.pow(self._g(RD_list[1]), 2) * tempE * (1 - tempE)
return 1 / (math.pow(self._q, 2) * tempSum)
I've got the functions e and g defined like so, and q is a constant:
Player.prototype.e = function(this, ratingList, rdList) {
// Stuff goes here
}
In Javascript you don't need o pass the self explicitly (Python is the "weird" one here, actually)
Player.prototype.e = function(rating_list, RD_list){
//replace "self" with "this" here:
var tempSum = 0; //if you don't use the "var", tempSum will be a global
// instead of a local
for(var i=0; i<rating_list.length; i++){ //plain old for loop - no foreach in JS
var tempE = this._E( ... ); //note that in JS, just like in Python,
//variables like this have function scope and
//can be accessed outside the loop as well
tempSum += Math.pow( ... ) //the Math namespace is always available
//Javascript doesn't have a native module system
}
return (...);
}
This should work all right.
The only tricky thing you need to know about this is that it is very promiscuous. This means that is is determined by how you call the function:
obj.e(); //if you do a method-like call, the this will be set to obj
However, there is no magic binding behind the scenes. The following works in python but does not work in Javascript:
f = obj.e
f(); //looks like a normal function call. This doesn't point to obj

Categories

Resources