I have code similar to following. in if statement i am doing the math operation as well as assigning to the lastChangedTime variable, this code works fine without minification, but after minification, even though it goes in if statement, the lastChangedTime is having value assigned by timeDiff. why is this happening.
var getLastUpdatedDurration = function (timeDiff) {
var lastChangedTime = timeDiff;
if ((lastChangedTime = Math.round(timeDiff / (1000 * 60 * 60 * 24 * 365))) > 0) {
lastChangedTime > 1 ? lastChangedTime += " years" : lastChangedTime += " year";
}
return lastChangedTime;
};
simplified minification code for this function looks like shown below. from the following code i was expecting to return 10 years. as after dividing value is assigned to t but it returns 100 which was initially assigned. can someone tell me whats wrong with following code.
var v = function (n) {
var i = 100,
t = i;
return t + ((t = Math.round(i / 10)) > 0 ? " years" : (t = Math.round(i / 10)) > 0 ? " seconds" : " milliseconds")
}
Related
pardon me for putting up another question on random number generation. I have a working solution as [function random_X_digits(digits)].
But in [function randnum3(digits)], I failed to understand why it loses rand (value) after recursive iteration it goes under if 'rand' < minimum xxxx digit number.
looking forward for some simple explanations. Thanks.
function random_X_digits(digits) {
let a = 10 ** (digits - 1);
let b = Math.random();
return Math.floor(a + b * 9 * a);
}
const n1 = random_X_digits(4); // XXXX digit random number
console.log("n1: " + n1);
function randnum2(digits) {
let rand = parseInt(10 ** digits * Math.random());
console.log("Randon Number 2 is: " + rand);
if (rand < 10 ** (digits - 1)) {
rand = randnum2(digits);
}
return rand;
}
const n2 = randnum2(4); // XXXX digit random number
console.log("n2: " + n2);
function randnum3(digits) {
let rand = parseInt(10 ** digits * Math.random());
console.log("Randon Number 3 is: " + rand);
if (rand < 10 ** (digits - 1)) {
rand = randnum3(digits); //! this is returning Undefined output. ???
}
this.rn = rand;
}
const nrn = new randnum3(4); // XXXX digit random number
const n3 = nrn.rn; //
console.log("n3: " + n3);
When a function doesn't have an explicit return statement, it returns undefined.
Your code works fine until rand is greater than 10** (digits-1). At that point it doesn't return rand, but sets a property in the randnum3 function. If you console.log randnum3 you will see that property.
console.log("n3: " + randnum3.rn);
So, a function that doesn't return explicitly, returns undefined. Fix the return statement (like in randnum2) and it will work properly.
Have the function TimeConvert(num) take the num parameter being passed and return the number of hours and minutes the parameter converts to (ie. if num = 63 then the output should be 1:3). Separate the number of hours and minutes with a colon.
Another example if input:126 then output: 2:06.
This is what I did and I do not understand why it is wrong. For an input of 126, it is giving me an output of 11:06.
function TimeConvert(num) {
if(num<60 && num>10){
return 0+":"+num
}
if(num<10){
return 0+":"+0+num
}
let object={
12:720,
11:660,
10:600,
9:540,
8:480,
7:420,
6:360,
5:300,
4:240,
3:180,
2:120,
1:60
}
let time=""
for (let key in object){
while(num>=object[key]){
time += key
num-= object[key]
}
}
return time+":"+num
}
As noted in comments, there are many ways to reduce minutes to hours and minutes. However, to address your question as to why your approach is failing:
Object keys are treated as strings, not numbers. Also, you have declared time as a string.
For your approach to work, you have to make BOTH these changes:
let time="" -> let time = 0
and
time += key -> time += parseInt(key)
Working snippet:
console.log(TimeConvert(126));
function TimeConvert(num) {
if(num<60 && num>10){
return 0+":"+num
}
if(num<10){
return 0+":"+0+num
}
let object={
12:720,
11:660,
10:600,
9:540,
8:480,
7:420,
6:360,
5:300,
4:240,
3:180,
2:120,
1:60
}
let time=0;
for (let key in object){
while(num>=object[key]){
time += parseInt(key)
num-= object[key]
}
}
if (num<10) { num = "0"+num;} // add leading 0 and coerce to string if num <10;
return time+":"+num
}
Why not use this algorithm
Get the number of times that 60 minutes is in the number argument
Get the remainder minutes
Concatenate both (with padding for the minutes)
Return the answer
const getHoursAndMinsString = (num) => {
if (num <= 0) {
return `0:00`
}
const hours = Math.floor(num / 60)
const mins = num % 60
return `${hours}:${mins.toString().padStart(2, "0")}`
}
Your object lookup is just encoding n=>n*60, but only for a subset of possible values so is arbitrarily limiting the range of values your function can operate on.
Removing that, and using floor and % to compute the hours and minutes respectively reduces the code down to:
function TimeConvert(num) {
let time = Math.floor(num / 60);
num = num % 60;
if (num < 10) { num = "0" + num; } // add leading 0 and coerce to string if num <10;
return time + ":" + num;
}
These calculations can also be done inline if you rather which reduces the code even further:
function TimeConvert(num) {
return Math.floor(num / 60) + ":" + ((num % 60) < 10 ? "0" : "") + (num % 60);
}
just watch out for negative values, or anything higher than 1440, which would overflow past 24 hours and you may want to start displaying with days.
I'm trying to validate in Javascript that a number is in increments of 50, if not, then throw a validation error. For example:
123 - invalid, can either be 100 or 150
272 - invalid, can either be 200 or 250 or 300
etc...
I'm thinking that the % remainder operator is what I need to use but not quite sure how to build a javascript validation rule to match this.
Are you looking for something like:
(val) => {
var remainder = val % 50;
if (remainder !== 0) {
var lower = val - remainder;
var higher = lower + 50;
throw new Error(val + ' - invalid, can either be ' + String(lower) + ' or ' + String(higher));
}
}
That could be reduced, but this way you can see the logic at work.
This is the math you want to preform:
Math.round(123/ 50)*50; //this gives 100
Math.ceil(123/ 50)*50; //this gives 150
and here is the validation function
function validate(number) {
var round = Math.round(number / 50) * 50;
var ceil = Math.ceil(number / 50) * 50;
if (number == round) { return console.log("valid"); }
return console.log(`${number} - invali, can eiher be ${round} or ${ceil}`);
}
I am trying to set a function that creates a random number between a range
I need to make it working with negative values so I can do
randomBetweenRange( 10, 20)
randomBetweenRange(-10, 10)
randomBetweenRange(-20, -10)
This is what I am trying, it is a bit confusing and at the moment randomBetweenRange(-20, -10) is not working..
function randomBetweenRange(a, b){
var neg;
var pos;
if(a < 0){
neg = Math.abs(a) + 1;
pos = (b * 2) - 1;
}else{
neg = -Math.abs(a) + 1;
var pos = b;
}
var includeZero = true;
var result;
do result = Math.ceil(Math.random() * (pos + neg)) - neg;
while (includeZero === false && result === 0);
return result;
}
How can I make it working?
ASSUMING you will always have the little value on first, this code will do the tricks, see the comment below and don't hesitate to ask !
var a=parseInt(prompt("First value"));
var b=parseInt(prompt("Second value"));
var result = 0;
// Here, b - a will get the interval for any pos+neg value.
result = Math.floor(Math.random() * (b - a)) + a;
/* First case is we got two neg value
* We make the little one pos to get the intervale
* Due to this, we use - a to set the start
*/
if(a < 0) {
if(b < 0) {
a = Math.abs(a);
result = Math.floor(Math.random() * (a + b)) - a;
}
/* Second case is we got two neg value
* We make the little one neg to get the intervale
* Due to this, we use - a to set the start
*/
} else {
if(b > 0) {
a = a*-1;
result = Math.floor(Math.random() * (a + b)) - a;
}
}
console.log("A : "+a+" | B : "+b+" | Int : "+(a+b)+"/"+Math.abs((a-b)));
console.log(result);
You have declared the variable 'pos' in the beginning itself. Then why do you declare it in the 'else' part? ( var pos = b;)
Hence, for this statement,
do result = Math.ceil(Math.random() * (pos + neg)) - neg;
'pos' will not have any value.
do result = Math.ceil(Math.random() * (pos + neg)) - neg;
Specifically Math.random() * (pos + neg) returns the wrong range. If pos = -20 and neg = -30, the range between pos and neg should be 10, but your operation returns -50. You should also add one to the range because its technically the amount of possibilities (ex: if you want to generate your function to return {0,1}, the range between pos and neg is 1, but there are two possibilities of numbers to return) and subtract another 1 from result because you're using Math.ceil
Your else clause also redeclares var pos
If you want to generate a number between -50 and 50 - Get a random number between 0 and 100 then subtract 50
var randomNumber = Math.floor(Math.random() * 101) - 50;
console.log(randomNumber);
I didn't think this was possible until console.log(); shown me that whats happening is impossible.
I can't understand how this is possible it's like those variables are being modified before code execution finishes.
I got this JavaScript code with debugging in it.
It's wrapped in this.
$('#buyAmountInput').keyup(function () {
var buyAmount = parseFloat($(this).val());
var totalPrice = 0;
var max = $(this).attr("max");
var min = $(this).attr("min");
if (buyAmount != $(this).val()) {
if (isNaN(buyAmount)) {
buyAmount = 1;
$(this).val('');
} else {
$(this).val(buyAmount);
}
} else {
if (buyAmount > max) {
buyAmount = max;
$(this).val(buyAmount);
} else if (buyAmount < min) {
buyAmount = min;
//$(this).val(buyAmount);
}
}
totalPrice = buyAmount * unitPrice;
//lots of code trimmed off here.
largessAmount = Math.round(buyAmount * largessRule.rebate) / 100;
////
console.log("Buy amount " + buyAmount + " LargessRebate " + largessRule.rebate);
console.log("Total Price " + totalPrice);
console.log("Largess Amount " + largessAmount);
console.log("New rate " + Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
console.log("No .moneyFormat() New rate " + Number(totalPrice / (buyAmount + largessAmount)));
console.log("( " + totalPrice + " / ( " + buyAmount + " + " + largessAmount + " ))");
////
$('#unitPrice').html(Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
});
Debug looks like this
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.71
No .moneyFormat() New rate 0.7083333333333334
( 4250 / (5000 + 1000))
function fastKeyListener content_script.js:208
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.00 //<- What happened here
No .moneyFormat() New rate 0.00008499830003399932 //<- What happened here
( 4250 / (5000 + 1000)) //<- Third line executed this will give good rate..
Even if the variables are global and this code is in a keypress up jQuery callback function.
The variables are printed before they are executed by console.log() and they are correct but the answer is dead wrong.
Here is the moneyFormat() which I don't think could be the problem could it?
var effective_bit = -2;
Number.prototype.moneyFormat = function () {
var num = this;
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * Math.pow(10, -effective_bit) + 0.50000000001);
cents = num % Math.pow(10, -effective_bit);
num = Math.floor(num / Math.pow(10, -effective_bit)).toString();
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ', ' + num.substring(num.length - (4 * i + 3));
if (effective_bit < 0) {
if (cents < 10 && effective_bit == '-2') cents = "0" + cents;
money = (((sign) ? '' : '-') + num + '.' + cents);
} else {
money = (((sign) ? '' : '-') + num);
}
return money;
};
I didn't post the whole code as it's very large, but you can see it live here
Just put into the Unit to buy of 4999, then scroll to 5000 it's all good.. try putting like 5001 or 50000 it will reset it to 5000 and give wrong answer in the process.
EDIT:
could of simplified the question to why does the console.log() functions evaluate incorrect answer if the same equation generated with the same variables just 1 line after in execution after gives correct answer, even on calculator.
Like some quantum going on here, bear with me there is nothing I could have done from 1 line to another line during that code-execution no breakpoints were set nothing plus those callbacks are functions generated in their own sandbox I believe so they are like ajax threads all working to complete sooner or later they all work separately from each other, so nothing working together here to mess it up. What you think could possibly happen here? some temporarily corruption or something?
This occurs sometimes when doing claulations using string variables.
Try converting the buyAmount and any variable that came from HTML to number before any calculation.
You can use the Number() function or parseFloat().
http://jsfiddle.net/rcdmk/63qas2kw/1/