How to replace NULL% by 0% - javascript

In my calculatePercents () method, I should get 0% instead of NULL%.
In my console.log, I get prints with the values NULL
calculatePercents() {
this.v.global.total.amount = this.v.global.cash.amount + this.v.global.sec.amount;
console.log("Cash => " + JSON.stringify(this.v.global.total.amount));
console.log('------------------------');
this.v.global.cash.percent = (this.v.global.cash.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100;
console.log(" Global cash " + JSON.stringify(this.v.global.cash.percent));
this.v.global.sec.percent = (this.v.global.sec.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100;
console.log(" NULL ???? ==> " + JSON.stringify(this.v.global.sec.percent));
var totPercent = (this.v.global.cash.percent + this.v.global.sec.percent);
this.v.global.total.percent = totPercent;
}
How I could get a 0 instead of NULL please.

you can use || operator to set zero
Eg:
this.v.global.total.percent = (totPercent||0);
for more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

with || if the first value is false (converted as boolean) then it will take the second, in that case it's used as a default value.
this.v.global.total.percent = totPercent || 0;

You can try this in your method;
if(this.v.global.cash.amount == null){
this.v.global.cash.amount = 0
}
if(this.v.global.sec.amount == null){
this.v.global.sec.amount = 0
}
And then you can do that; (your method)
calculatePercents() {
this.v.global.total.amount = this.v.global.cash.amount + this.v.global.sec.amount;
console.log("Cash => " + JSON.stringify(this.v.global.total.amount));
console.log('------------------------');
this.v.global.cash.percent = (this.v.global.cash.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100;
console.log(" Global cash " + JSON.stringify(this.v.global.cash.percent));
this.v.global.sec.percent = (this.v.global.sec.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100;
console.log(" NULL ???? ==> " + JSON.stringify(this.v.global.sec.percent));
var totPercent = (this.v.global.cash.percent + this.v.global.sec.percent);
this.v.global.total.percent = totPercent;
}
And your veriable type is can be "let".
Simple Code:
let a = null;
if(a==null){
a=0
}
console.log(a);
// output: 0

Related

time diffrence in double digit

i want to display TravelTimeHoursDiff and TravelTimeMinutesDiff in double digit now my time is shown as 7:0 i want to display like 07:00
if ($scope.DispatchStatus.ArrivalTime != undefined){
var today = $rootScope.getSysDate().split(" ");
var timeArrival = new Date(today[0] + ' ' + $scope.DispatchStatus.ArrivalTime);
var TravelTime = new Date(today[0] + ' ' + $scope.Route.TravelTime);
var timeArrivalHours = timeArrival.getHours();
var TravelTimeHoursDiff = timeArrivalHours - TravelTime.getHours() ;
var TravelTimeMinutesDiff = (timeArrival.getMinutes() - TravelTime.getMinutes());
if(TravelTimeHoursDiff < 0 || (TravelTimeHoursDiff <= 0 && TravelTimeMinutesDiff < 0) || (TravelTimeHoursDiff == 0 && TravelTimeMinutesDiff == 0)){
$scope.formvalidationbit = $scope.DispatchStatusAddForm[fieldName].$invalid = true;
angular.element('#' + fieldName).addClass('ng-invalid');
angular.element('#' + fieldName).removeClass('ng-valid');
$scope.DispatchStatusAddForm.$valid = false;
var errorbit = 1;
}else{
if (isNaN(TravelTimeHoursDiff)) {
TravelTimeHoursDiff = '--';
}
if (isNaN(TravelTimeMinutesDiff)) {
TravelTimeMinutesDiff = '--';
}
if(TravelTimeMinutesDiff <0){
TravelTimeMinutesDiff = TravelTimeMinutesDiff * (-1);
}
$scope.TravelTime = TravelTimeHoursDiff + ':' + TravelTimeMinutesDiff;
}
}
Just add leading 0 to values smaller then 10, something like:
let addLeadingZero(v){
return v < 10 ? ("0" + v) : v;
}
$scope.TravelTime = addLeadingZero(TravelTimeHoursDiff) + ':' + addLeadingZero(TravelTimeMinutesDiff);

How to calculate `lib.ema` starting from the previous period?

Hi I need to calculate EMA in Zenbot, but starting from the previous period, how does one do that?
return function ema (s, key, length, source_key) {
if (!source_key) source_key = 'close'
if (s.lookback.length >= length) {
var prev_ema = s.lookback[0][key]
if (typeof prev_ema === 'undefined' || isNaN(prev_ema)) {
var sum = 0
s.lookback.slice(0, length).forEach(function (period) {
sum += period[source_key]
})
prev_ema = sum / length
}
var multiplier = 2 / (length + 1)
s.period[key] = (s.period[source_key] - prev_ema) * multiplier + prev_ema
}
}
}
Recently figured out the same thing, you can use this commit as a reference.
+++ b/extensions/strategies/wavetrend/strategy.js
## -0,0 +1,172 ##
...
+ onPeriod: function (s, cb) {
+ if (s.period.wto) {
+ s.signal = null // hold
+ let prev_wto = s.lookback[0].wto
+ let wto = s.period.wto
+ let prev_hcl3 = s.lookback[0].hcl3
+ let hcl3 = s.period.hcl3
+ let prev_ema = s.lookback[0].ema
+ let ema = s.period.ema
+
+ if (!s.sell_signal_close)
+ s.sell_signal_close = 0
+ if (!s.buy_signal_close)
+ s.buy_signal_close = 0
+ if (!s.sell_pct_orig)
+ s.sell_pct_orig = s.sell_pct
+ if (!s.buy_pct_orig)
+ s.buy_pct_orig = s.sell_pct

Trying to make loop exit , but it currently just continues looping for 100 times

I am trying to make so when the looping of 100 hits on the character exits the loop when the life dice rolls to 0. How it currently is is all gets looped 100 times. I am not quite sure how I need to go about solving this, any tips would be helpful. My code is below.
function addChar(fname, lname, speed, agility, wep, outfit, mood) {
this.fname = fname;
this.lname = lname;
this.speed = speed;
this.agility = agility;
this.wep = wep;
this.outfit = outfit;
this.mood = mood;
this.special = function(specialMove) {
specialMove();
}
this.jumpKick = function() {
var jmpkckTimes = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write("He jumpkicks " + jmpkckTimes + " times. ");
if (jmpkckTimes > 70) {
document.write("He enters rage mode! ");
} else {
document.write("He does not have enough kicks for rage mode. ");
}
}
this.hits = function() {
var allHits = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write(" He gets attacked for " + allHits + " HP.");
}
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
if (life > 0) {
document.write(" The life dice rolls a " + life + ". You have survived! For now...");
} else {
document.write(" The life dice rolls a " + life + ". You have died!");
}
}
}
var myChar = new addChar('Johhny', 'Kicker', 10, 7, 'Ancient Greataxe', 'Barrows', 'angry');
document.write(myChar.fname + " " + myChar.lname + "'s speed is " + myChar.speed + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s agility is " + myChar.agility + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s weapon of choice is: " + myChar.wep + "<br>");
document.write(myChar.fname + " " + myChar.lname + " feels " + myChar.mood + "<br>");
document.write(myChar.fname + " " + myChar.lname + " attempts his special: ");
myChar.special(myChar.jumpKick)
for (i = 1; i < 101; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
function myOutfit() {
document.getElementById("demo").innerHTML = ("He is wearing " + myChar.outfit)
}
var start = Date.now();
var response = prompt("Do you think my character has what it takes?", "");
var end = Date.now();
var elapsed = (end - start) / 1000;
console.log("You took " + elapsed + " seconds" + " to type: " + response);
You need to have a way to communicate outside of the object, of what is happening inside the object.
For example, when something happens in a function, like lifes() or hits(), you should assign a value to a variable on the object to retain state. That way you can access the state from the for loop.
Example:
this.isAlive = true; // starting condition
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
this.isAlive = (life > 0);
if (this.alive) {
document.write('you survived');
} else {
document.write('you died');
}
Now in your for loop, you can access isAlive:
// loop until 100 attempts or you die, which ever comes first
for (i = 1; i < 101 && myChar.isAlive; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
well in general you can break out of foor loops aswell as prevent further execution of a foor loop and continue the next iteration:
for (var i = 0; i < 10; i++) {
if (i == 4) continue;
if (i == 8) break;
console.log(i);
}
this will basically print: 0, 1, 2, 3, 5, 6, 7
(as you can see it kind of skipped 4)
(it will also work in while / do while loops)
so in your case you could check if the return value of one of your functions is true or false or do some other kind of conditional checking in order to break out of the loop.
or similar to how Rob Brander wrote in his answer:
var maxTurns = 100;
var turns = 0;
while (myChar.isAlive && ++turns <= maxTurns) {
myChar.hits();
myChar.lifes();
}
console.log("character is: " + myChar.isAlive ? "alive" : "dead");
console.log("after: " + turns + " turns.");

Error : is not a function. How can I fix it?

This is my lift programm. But I have error.
var person = {
name: "Roman",
position: 2,
goal: 9
};
var lift = {
getPosition : function() {
var x = Math.floor((Math.random() * 10) + 1);
return x;
} ()};
console.log("Ok " + person.name + "! You are at " + person.position + " floor");
console.log("Lift is at " + lift.getPosition() + " floor");
Error lift.getPosition is not a function.
How can I fix it??
you code looks broken:
var lift = {
getPosition : function() {
var x = Math.floor((Math.random() * 10) + 1);
return x;
} ()};
it seems this should be
var lift = {
getPosition : function() {
var x = Math.floor((Math.random() * 10) + 1);
return x;
}
};
When you declared getPosition you assigned this property a self invoked anonymous function. (The () at the end, self invokes it)
var lift = {
getPosition: function() {
var x = Math.floor((Math.random() * 10) + 1);
return x;
}()
};
You can remove them () and call the method like you did "lift.getPosition()":
var lift = {
getPosition: function() {
var x = Math.floor((Math.random() * 10) + 1);
return x;
}
};
console.log("Lift is at " + lift.getPosition() + " floor");
or leave them and just call the property without the () "lift.getPosition":
var lift = {
getPosition: function() {
var x = Math.floor((Math.random() * 10) + 1);
return x;
}()
};
console.log("Lift is at " + lift.getPosition + " floor");
But that would return the same value every time you use it, because it is only executed once. It really depends on what you are trying to accomplish.

Javascript function - works in IE, not in chrome

To preface this, we are a small organization and this system was built by someone long ago. I am a total novice at javascript so I have trouble doing complicated things, but I will do my best to understand your answers. But unfortunately redoing everything from scratch is not really an option at this point.
We have a system of collecting data where clients use a login to verify a member ID, which the system then uses to pull records from an MS Access database to .ASP/html forms so clients can update their data. One of these pages has the following function that runs on form submit to check that data in fields a/b/c sum to the same total as d/e/f/g/h/i. It does this separately for each column displayed (each column is a record in the database, each a/b/c/d/e/f is a field in the record.)
The problem is with this section of the function:
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
etc.
It should use javascript FOR to loop through each record and test to see if they sum to the same thing.
In Firefox and IE this is working properly; the fields sum properly into "sumByType" and "sumByTrack". You can see below I added a little alert to figure out what was going wrong:
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
In Chrome, that alert tells me that the components of "sumByType" and "sumByTrack" (the various "milesXXXXX" variables) are undefined.
My question is: Why in Chrome is this not working properly, when in IE and FFox it is? Any ideas?
Full function code below:
function submitCheck(formy, recCnt) {
//2/10/03: added milesQuad
//---------------checks Q#4 that Line Mileage by type is the same as by track
var milesElev = new Array();
var milesSurf = new Array();
var milesUnder = new Array();
var milesSingle = new Array();
var milesDouble = new Array();
var milesTriple = new Array();
var milesQuad = new Array();
var milesPent = new Array();
var milesSex = new Array();
var sumByType = 0;
var milesLineTrack = new Array(); //this is for Q5 to compare it to mileage by trackage
var j = 0; var sumByTrack = 0; var liney; var yrOp;
//var str = "document.frm.milesElev" + j;
//alert(str.value);
for (var i in document.frm) {
if (i.substring(0, i.length - 1) == "milesElev") {
milesElev[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSurf") {
milesSurf[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesUnder") {
milesUnder[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSingle") {
milesSingle[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesDouble") {
milesDouble[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesTriple") {
milesTriple[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesQuad") {
milesQuad[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesPent") {
milesPent[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSex") {
milesSex[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length -1) == "milesLineTrack") {
milesLineTrack[parseInt(i.substring(i.length-1, i.length))] = document.frm[i].value; } //12/13/02 used to be parseFloat(document.frm[i].value)
if (i.substring(0,5)=="Lines") {
liney = document.frm[i].value;
if (parseInt(liney)<1 || isNaN(liney)) {
alert("Each mode must have at least 1 line. Please correct the value in question #2.");
document.frm[i].select(); return false; }}
if (i.substring(0,8)=="yearOpen") {
yrOp = document.frm[i].value;
if (parseInt(yrOp)<1825 || isNaN(yrOp)) {
alert("Please enter a year after 1825 for question #3");
document.frm[i].select(); return false; }
}
}
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
//---------------to round sumByTrack and sumByType from a long decimal to a single decimal place, like frm 7.89999998 to 7.9.
sumByTrack = sumByTrack * 10;
if (sumByTrack != parseInt(sumByTrack)) {
if (sumByTrack - parseInt(sumByTrack) >= .5) {
//round up
sumByTrack = parseInt(sumByTrack) + 1; }
else { //truncate
sumByTrack = parseInt(sumByTrack); }}
sumByTrack = sumByTrack / 10;
sumByType = sumByType * 10;
if (sumByType != parseInt(sumByType)) {
if (sumByType - parseInt(sumByType) >= .5) {
//round up
sumByType = parseInt(sumByType) + 1; }
else { //truncate
sumByType = parseInt(sumByType); }}
sumByType = sumByType / 10;
//-------------end of rounding ---------------------------
if (sumByType != sumByTrack) {
if (isNaN(sumByType)) {
sumByType = "(sum of 4.a., b., and c.) "; }
else {
sumByType = "of " + sumByType; }
if (isNaN(sumByTrack)) {
sumByTrack = "(sum of 4.d., e., f., g., h., and i.) "; }
else {
sumByTrack = "of " + sumByTrack; }
alert("For #4, the 'End-to-End Mileage By Type' " + sumByType + " must equal the 'End-to-end Mileage By Trackage' " + sumByTrack + ".");
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
return false;
}
//alert (milesLineTrack[j] + " " + milesSingle[j] + " " + 2*milesDouble[j] + " " + 3*milesTriple[j] + " " + 4*milesQuad[j] + " " + 5*milesPent[j] + " " + 6*milesSex[j]);
var singDoubTrip = (milesSingle[j] + 2*milesDouble[j] + 3*milesTriple[j] + 4*milesQuad[j] + 5*milesPent[j] + 6*milesSex[j])
//----------round singDoubTrip to one digit after the decimal point (like from 6.000000001 to 6.0)
singDoubTrip = singDoubTrip * 10;
if (singDoubTrip != parseInt(singDoubTrip)) {
if (singDoubTrip - parseInt(singDoubTrip) >= .5) {
//round up
singDoubTrip = parseInt(singDoubTrip) + 1; }
else { //truncate
singDoubTrip = parseInt(singDoubTrip); }}
singDoubTrip = singDoubTrip / 10;
//----------end round singDoubTrip-----------------------------------------
if (parseFloat(milesLineTrack[j]) != singDoubTrip) {
//var mlt = milesLineTrack[j];
//if isNaN(milesLineTrack[j]) { mlt =
alert("For column #" + (j+1) + ", the mainline passenger track mileage of " + milesLineTrack[j] + " must equal the single track plus 2 times the double track plus 3 times the triple track plus 4 times the quadruple track plus 5 times the quintuple track plus 6 times the sextuple track, which is " + singDoubTrip + ".");
return false;
}
}
//---------------------end of checking Q#4----------------
//return false;
}
I think for (var i in document.frm) is the problem. You should not enumerate a form element, there will be plenty of unexpected properties - see Why is using "for...in" with array iteration a bad idea?, which is especially true for array-like objects. I can't believe this works properly in FF :-)
Use this:
var ele = document.frm.elements; // or even better document.getElementById("frm")
for (var i=0; i<ele.length; i++) {
// use ele[i] to access the element,
// and ele[i].name instead of i where you need the name
}
Also, you should favour a loop over those gazillion of if-statements.

Categories