I have this function below, i am trying to compare negative numbers, I'm using unix time so the time difference is negative because the date has already passed, but I still want to use it, when the within5Days variable is a negative four(-4) the within5DaysBoolean variable is not set to false, it is still being set to true, I don't know what I'm missing here, any help
function timeDifference2(next, now) {
var sPerMinute = 60;
var sPerHour = sPerMinute * 60;
var sPerDay = sPerHour * 24;
var sPerMonth = sPerDay * 30;
var sPerYear = sPerDay * 365;
var sPerTwoDays = sPerDay * 2;
var elapsed = next - now;
return Math.floor(elapsed / 3600);
}
var within5Days = timeDifference2(unixTime, currentUnixTime);
if (within5Days < 120 && within5Days > -2) {
var within5DaysValue = within5Days;
var within5DaysBoolean = true;
} else if (within5Days > 120 || within5Days < -2) {
var within5DaysValue = within5Days;
var within5DaysBoolean = false;
}
you may try as follows using parseFloat
if((parseFloat(within5Days) < 120 && parseFloat(within5Days) > -2)) {
var within5DaysValue = within5Days;
var within5DaysBoolean = true;
} else if ((parseFloat(within5Days) > 120) || parseFloat(within5Days) < -2)) {
var within5DaysValue = within5Days;
var within5DaysBoolean = false;
}
Related
Im currently checking what the closest number would be compared to an array:
var testarray1 = [4054,4938,4983,1928,8833];
var test = 5000;
var result = testarray1.reduce(function(prev, curr) {
return (Math.abs(curr - postcode) < Math.abs(prev - postcode) ? curr : prev);
}
This works fine.
but when i have it like multi numbers in one, it dosent work:
var testarray1 = ["4000-5595","4400-4720"];
var test = 4630;
for (var x =0; x < testarray1.length; x++) {
var selectedPostcode = testarray1[x][0];
var splitted = selectedPostcode.split("-");
var from = parseInt(splitted[0]);
var to = parseInt(splitted[1]);
if (postcode >= from && postcode <= to) {
return selectedPostcode;
break;
}
}
in the example code above, it would return "4000-5595", but how can i do so it selects the closest one, in this case it would be the "4400-4720"?
Try like below. Explanation is in comments.
var testarray1 = ["4000-5595", "4400-4720"];
var postcode = 4630;
// Take two variables to set difference and result
// set difference default value to -1
var difference = -1;
var result = "";
for (var x = 0; x < testarray1.length; x++) {
// use testarray1[x] instead of testarray1[x][0]
var selectedPostcode = testarray1[x];
var splitted = selectedPostcode.split("-");
var from = parseInt(splitted[0]);
var to = parseInt(splitted[1]);
if (postcode >= from && postcode <= to) {
// get difference
let currDiff = Math.abs(postcode - from) + Math.abs(postcode - to);
// difference = -1 means there is no existing value so set current as result
// check current difference is less than existing one.
if (difference == -1 || currDiff < difference) {
difference = currDiff;
result = selectedPostcode;
}
}
}
console.log(result);
If you want closest value based on minimum difference from either one of the value then use let currDiff = Math.min(Math.abs(postcode - from), Math.abs(postcode - to));.
var testarray1 = ["4000-5595", "4400-4720", '4800-5000'];
var postcode = 4630;
// Take two variables to set difference and result
// set difference default value to -1
var difference = -1;
var result = "";
for (var x = 0; x < testarray1.length; x++) {
// use testarray1[x] instead of testarray1[x][0]
var selectedPostcode = testarray1[x];
var splitted = selectedPostcode.split("-");
var from = parseInt(splitted[0]);
var to = parseInt(splitted[1]);
if (postcode >= from && postcode <= to) {
// get difference
let currDiff = Math.min(Math.abs(postcode - from), Math.abs(postcode - to));
// difference = -1 means there is no existing value so set current as result
// check current difference is less than existing one.
if (difference == -1 || currDiff < difference) {
difference = currDiff;
result = selectedPostcode;
}
}
}
console.log(result);
You have to check for every interval and check if previous ans is closet or current interval is closet and change ans accordingly like this.
var testarray1 = ['4000-5595', '4400-4720']
var test = 4630
let ans
for (var x = 0; x < testarray1.length; x++) {
var selectedPostcode = testarray1[x]
var splitted = selectedPostcode.split('-')
var from = parseInt(splitted[0])
var to = parseInt(splitted[1])
if (ans) {
if (ans[0] < from || ans[1] > to) ans = [from, to]
} else {
if (test >= from && test <= to) {
ans = [from, to]
}
}
}
console.log(ans.join('-'))
I have written a program in javascript (Node) that is supposed to calculate the RSI using the Binance api.
The only thing is that my program does not calculate the "real" RSI. For example, if i set my period to be 14 days, as the formula says - I get an RSI value equal to ~28 and the real RSI being 38.
If i change the period and set it to 20, i get an RSI pretty close to the real one, with mine being 39 and the real one being 38.
I can't figure it out.what am i doing wrong. Any suggestion?
Here is my code :
const binance = require('node-binance-api')().options({
APIKEY: 'xxx',
APISECRET: 'xxx',
useServerTime: true,
test: true // True = SandboxMode
});
/* VARIABLES */
let listClose = [];
let changeUp = 0;
let changeDown = 0;
let last_closeHigh = 0;
let last_closeLow = 0;
let current_time = Date.now();
let period = 20;
function calculateRSI() {
console.log("Generating RSI");
binance.candlesticks("ETHBTC", "1d", (error, ticks, symbol) => {
for (i = 0; i < ticks.length; i++) {
let last_tick = ticks[i];
let [time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored] = last_tick;
listClose.push(close);
if (i == ticks.length -1 ) {
for (x = 0; x < ticks.length; x++) {
previous_close = (parseFloat(listClose[x-1]));
current_close = (parseFloat(listClose[x]));
// HIGH
if (current_close > previous_close) {
upChange = current_close - previous_close;
changeUp += upChange;
if (x == ticks.length -1) {
last_closeHigh = current_close - previous_close;
}
}
// LOW
if (previous_close > current_close) {
downChange = previous_close - current_close;
changeDown += downChange;
if (x == ticks.length - 1) {
last_closeLow = previous_close - current_close;
}
}
if (x == ticks.length-1) {
AVGHigh = changeUp / period;
AVGLow = changeDown / period;
Upavg = (AVGHigh * (period -1) + last_closeHigh) / (period);
Downavg = (AVGLow * (period -1) + last_closeLow) / (period);
RS = Upavg / Downavg;
RSI = (100 - (100 / (1 + RS)));
console.log(RSI);
return RSI;
}
}
}
}
}, {
limit: period,
endTime: current_time
});
}
calculateRSI();
Sorry for jumping on this late...but the reason for this is using the Sandbox.
Binance Sandbox is awful and should never be used, it gives bad values.
I'm making a function that takes in user input and must display it as 7 characters i.e. if 42.54 was entered it would display 0004254. My issue is that I'm taking an integer and applying it to an array causing an undefined error when applying the 0's
function BackDataDefaultInput() {
// Balance
var count;
var newNum = "";
var balanceText = document.getElementById('balanceNumBox').value;
count = balanceText.length;
while (count > 0 && count < 7) {
newNum += '0';
count++
}
var formattedBalance = parseInt(balanceText, 10) * 100;
for (var i = 0; i < balanceText.length; i++) {
formattedBalance[i] = new Array();
// Error here showing as undefined for formattedBalance[i]
newNum += formattedBalance[i];
}
This code worked before I had to multiply it by 100 to get the right format. as I was just appending two strings. Can somebody help me think of a solution?
Primitives (like numbers) are immutable; if you have
var formattedBalance = parseInt(balanceText, 10) * 100;
you can't proceed to reassign index properties like
formattedBalance[i] = new Array();
It would probably be easier to remove the (possible) period with a regex and use padStart rather than mess with arrays:
function BackDataDefaultInput() {
const balanceText = '42.54'; // document.getElementById('balanceNumBox').value;
console.log(
balanceText
.replace(/\./g, '')
.padStart(7, '0')
);
}
BackDataDefaultInput();
Try to use following function.
var balanceText = "42.54"; //document.getElementById('balanceNumBox').value;
var formattedBalance = balanceText * 100;
function formatInteger(str, max) {
str = str.toString();
return str.length < max ? formatInteger("0" + str, max) : str;
}
console.log(formatInteger(formattedBalance, 7));
Answer to my question in case it helps anyone that comes across this page:
function BackDataDefaultInput() {
var balanceText = document.getElementById('balanceNumBox').value;
var balance = parseFloat(balanceText) * 100;
balanceText = String(balance);
while (balanceText.length > 0 && balanceText.length < 7) {
balanceText = '0' + balanceText;
}
}
I am trying to call function sumWH after the completion of the function sumMon1. Both functions get the text from labels, sum up their values, and update a counter label. The code that I have attempted to use to call sumHW after sumMon1 is below and does not work.
$.when(sumMon1()).done(function () {
sumWH();
});
the sum functions look like this:
<script>
$.when(sumMon1()).done(function () {
sumWH();
});
function sumWH() {
alert(event.target);
//Get Friday AM Out Value
var a = parseInt($('[id$="lblWeek1FridayTotalHrs"]').val(), 10) || 0;
//Get Friday AM IN Value
var b = parseInt($('[id$="lblWeek2FridayTotalHrs"]').val(), 10) || 0;
//Get Friday PM Out Value
var c = parseInt($('[id$="lblWeek1SaturdayTotalHrs"]').val(), 10) || 0;
//Get Friday AM IN VALUE
var d = parseInt($('[id$="lblWeek2SaturdayTotalHrs"]').val(), 10) || 0;
//Get Friday AM Out Value
var e = parseInt($('[id$="lblWeek1SundayTotalHrs"]').val(), 10) || 0;
//Get Friday AM IN Value
var f = parseInt($('[id$="lblWeek2SundayTotalHrs"]').val(), 10) || 0;
//Get Friday PM Out Value
var g = parseFloat($('[id$="lblWeek1MondayTotalHrs"]').val(), 10);
//Get Friday AM IN VALUE
var h = parseInt($('[id$="lblWeek2MondayTotalHrs"]').val(), 10) || 0;
//Get Friday AM Out Value
var i = parseInt($('[id$="lblWeek1TuesdayTotalHrs"]').val(), 10) || 0;
//Get Friday AM IN Value
var j = parseInt($('[id$="lblWeek2TuesdayTotalHrs"]').val(), 10) || 0;
//Get Friday PM Out Value
var k = parseInt($('[id$="lblWeek2WednesdayTotalHrs"]').val(), 10) || 0;
//Get Friday AM IN VALUE
var l = parseInt($('[id$="lblWeek1WednesdayTotalHrs"]').val(), 10) || 0;
//Get Friday AM Out Value
var m = parseInt($('[id$="lblWeek2ThursdayTotalHrs"]').val(), 10) || 0;
//Get Friday AM IN Value
var n = parseInt($('[id$="lblWeek1ThursdayTotalHrs"]').val(), 10) || 0;
var result = a + b + c + d + e + f + g + h + i + j + k + l + m + n;
if (result > 0 && result < 81 && !isNaN(result)) {
$('[id$="txtTotalHours"]').html(result);
} else if (result == 0) {
$('[id$="txtTotalHours"]').html(0);
} else if (isNaN(result)) {
$('[id$="txtTotalHours"]').html(result);
}
}
</script>
<script>
$(document).ready(function () {
sumMon1();
$('[id$="txtWeek1MondayPM_OUT"], [id$="txtWeek1MondayAM_OUT"]').on("blur", function () {
sumMon1();
});
});
function sumMon1() {
//Get Monday AM Out Value
var Out2Dec = $('[id$="txtWeek1MondayAM_OUT"]').val();
//split dec and whole AM OUT
var OutAmDec = Out2Dec % 1;
var OutAMWhole = Math.floor(Out2Dec);
if (OutAMWhole < 12 && OutAMWhole != 0 && !isNaN(OutAMWhole)) {
OutAMWhole += 12;
}
//Get Monday AM IN Value
var In2Dec = $('[id$="txtWeek1MondayAM_IN"]').val();
//split dec and whole AM IN
var InAmDec = In2Dec % 1;
var InAmWhole = Math.floor(In2Dec);
//Get Monday PM Out Value
var Out1Dec = $('[id$="txtWeek1MondayPM_OUT"]').val();
//split dec and whole PM OUT
var OutPmDec = Out1Dec % 1;
var OutPMWhole = Math.floor(Out1Dec);
if (OutAMWhole < 12 && OutAMWhole != 0 && !isNaN(OutAMWhole)) {
OutPMWhole += 12;
}
//Get Monday AM IN VALUE
var In1Dec = $('[id$="txtWeek1MondayPM_IN"]').val();
//split dec and whole PM IN
var InPmDec = In1Dec % 1;
var InPMWhole = Math.floor(In1Dec);
//calculate times
var InAmVal = (InAmWhole * 60) + (InAmDec * 100);
var OutAmVal = (OutAMWhole * 60) + (OutAmDec * 100);
var InPmVal = (InPMWhole * 60) + (InPmDec * 100);
var OutPmVal = (OutPMWhole * 60) + (OutPmDec * 100);
var Difference = (OutAmVal - InAmVal) + (OutPmVal - InPmVal);
var result = Difference / 60;
//display result
if (result > 0 && !isNaN(result)) {
$('[id$="lblWeek1MondayTotalHrs"]').html(result.toFixed(2));
} else {
var value2 = (result.toFixed(2) * -1);
$('[id$="lblWeek1MondayTotalHrs"]').html(value2);
}
}
</script>
The sum functions are located in separate script tags. sumMon1 is set to go on blur from a series of textboxes.
Is this there a way to make this function work or is there a better way to accomplish this?
jQuery.when is for async functions.
async is something like setInterval or jQuery.ajax.
And except async stuff, JavaScript (Or almost any other languages as well) run codes from top to the bottom sequentially.
Your code is not using asynchronous things. so simply do
sumMon();
sumWH();
I'm trying to solve this leetcode problem here: https://leetcode.com/problems/next-closest-time/description/.
Simply my solution is to try every combination that is valid and then set my ans variable to the one that is closest to the original time. It does print out all the combinations however the diff variable never changes. In the for loop after (if cur.length ==4) it prints every possible combination because it still thinks that diff is 9007199254740991. Also when I assign ans to cur.slice(), I receive a blank array. Even when I uncomment it in the nextClosestTime function I still have the same issue.
/**
* #param {string} time
* #return {string}
*/
var diff = 9007199254740991;
function calcSeconds(digits) {
var hours = (digits[0] * 10) + digits[1];
var seconds = (digits[2] * 10) + digits[3];
return (hours * 3600) + (seconds * 60);
}
function nextClosestTime(time) {
var digits = [];
// diff = 9007199254740991;
var cur = [];
var ans = [];
for (var i = 0; i < time.length; i++) {
if (isFinite(time.charAt(i))) {
digits.push(parseInt(time.charAt(i)));
}
}
var target = calcSeconds(digits);
nch(digits, cur, diff, target, ans);
return ans;
};
function nch(digits, cur, diff, target, ans) {
if (cur.length == 4) {
var curSec = calcSeconds(cur);
if (Math.abs(curSec - target) < diff) {
console.log(cur);
diff = Math.abs(calcSeconds(digits) - calcSeconds(cur));
//ans = cur.slice();
}
return;
}
for (var i = 0; i < digits.length; i++) {
if ((((cur[0] * 10) + cur[1]) >= 24) || (((cur[2] * 10) + cur[3]) >= 60)) {
return;
}
cur.push(digits[i]);
nch(digits, cur, diff, target, ans);
cur.pop()
}
}