setTimeout does not work with medium-sized negative numbers - javascript

If you call setTimeout with a small or large negative number, the callback is run immediately, but with a medium-sized negative number, the callback is never run. Can someone explain this?
// Y and Z are printed, but not X
var x = -7677576503;
var y = -1000000000;
var z = -10000000000;
setTimeout(function () {
console.log('x');
}, x);
setTimeout(function () {
console.log('y');
}, y);
setTimeout(function () {
console.log('z');
}, z);
JSFiddle version
(tested on Chromium 57.0.2987.98 and on Firefox 50.1.0)

I think I have the answer.
according to MDN:
Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally.
the browser is converting this value to a 32-bit signed int.
so when it sees the values you've passed we can assume it is actually acting on the ones it converts to that type, and the ECMAScript specification says the return values from bitwise operations must be a 32-bit int.
Runtime Semantics: Evaluation
The production A : A # B, where # is one of the bitwise operators in the productions above, is evaluated as follows:
... [snipped].
Return the result of applying the bitwise operator # to lnum and rnum. The result is a signed 32 bit integer.
so if we put that together and test the values you've given:
x | 0 === 912358089, so the timeout will eventually be executed.. just in a while.
y | 0 === -1000000000, and the callback is fired immediately*.
z | 0 === -1410065408, still a negative, still fired immediately*.
*all tests done in chrome latest stable
you can test this with other negatives that would result in a positive when converted to a 32-bit signed int.
-7000000000 | 0 would result in 1589934592, and calling setTimeout(fn, -7000000000) doesn't appear to fire... today.
keeping in mind, this is my best guess at what is happening. good luck!
edit: thanks to Vivek Athalye, I think I have confirmation this is what is happening.
-4294967290000 | 0 === 6000, and if you run setTimeout(_ => console.log(1), -4294967290000) that fires in aprox. 6 seconds.

Related

Dynamically changing variables type

I am building a factorization program and I would like to change each BigInt type to regular Numbers when number <= Number.MAX_SAFE_INTEGER.
Instead of coding two functions for each case, it would be nice if I could keep it all into one function which could vary variables types accordingly (something like let myVar = 3n || 3 I guess).
function Factorize(dividend) {
let divisor = 2n;
//if number <= Number.MAX_SAFE_INTEGER then let divisor = 2. Same for all other bigInts.
let method1 = [], method2 = [];
while (dividend > 1n) {
if (dividend % divisor === 0n) {
method1.push(`${divisor}`);
method2.push(`${dividend} / ${divisor}`);
dividend /= divisor;
} else {
divisor++
};
};
return {
default: method1,
detailed: method2,
get isPrime() {
return this.default.length === 1 && this.default[0] !== 2;
}
};
};
const number = parseInt(prompt());
console.log(Factorize(BigInt(number)));
Thanks for your help.
What's the difficulty? Your comment contains half the required code already:
if (dividend <= Number.MAX_SAFE_INTEGER) {
divisor = 2;
dividend = Number(dividend);
}
And then you only need to replace the two strict equality comparisons === 0n and !== 2 with their non-strict variants. 0 == 0n returns true, 0n === 0n returns false.
Some other things worth mentioning:
(1) This method for factorization is extremely slow. There are prime numbers well below Number.MAX_SAFE_INTEGER for which this will take months. Depending on your use case, limiting the input size or implementing some sort of timeout (e.g., returning an error if a certain number of iterations wasn't enough to find the complete result) may be more important than supporting BigInts at all. (For inputs that have only small prime factors, even extremely huge inputs will still terminate quickly, so it's certainly possible to exceed Number range (even Number.MAX_VALUE) while still only taking a few milliseconds.)
(2) Using parseInt to get your input means that you're limiting yourself to Number precision; converting that Number to a BigInt afterwards doesn't bring the lost bits back. For example, if someone enters '12157665459056928801' (which is 3n ** 40n), parseInt will truncate that and your program will hence compute the wrong result. To avoid that, use the fact that the BigInt() constructor can convert strings directly, i.e.: BigInt(prompt()).
(3) While it's sometimes possible to write code that can work on both Numbers and BigInts, doing so is generally not recommended (and often not even useful), because the two types of values (intentionally!) behave differently in a number of ways (otherwise we wouldn't need both of them), so there is a large risk of such code not doing what you think it'll do. In this particular case it should be okay; I'm just advising not to generalize from this example.

Can crypto.getRandomValues(new Uint32Array(1))[0] / lim ever be negative?

Curious whether the expression crypto.getRandomValues(new Uint32Array(1))[0] / lim can ever be negative.
The code I'm converting puts a Math.abs wrapper around it, but some of us think that it's impossible for it to be negative, so just wanted to see what the rest of you think?
var lim = Math.pow(2, 32) - 1;
crypto.getRandomValues(new Uint32Array(1))[0] / lim);
This is the related question for more context:
Converting getRandomValue.browser from cuid to Typescript?
The library has a getRandomValue() nodejs function that looks like this:
import * as crypto from "crypto"
var lim = Math.pow(2, 32) - 1;
export function getRandomValue () {
return Math.abs(crypto.randomBytes(4)
.readInt32BE(0) / lim)
}
I think for the browser, the Math.abs call was kept even though it seems it is not necessary, and quite possibly incorrect.
In this case, the use of Math.abs() would be wrong!
The value in question, so says the declaration above, is UInt32 ... unsigned 32-bit integer.
This simply means that the leftmost bit (most significant bit) is not to be interpreted as a sign-bit. This does not, however, prevent you from inadvertently using the value in some context which would assume that MSB=1 means "negative."
Nonetheless, it would be wrong for you to use abs() because this would convert the entire bit-pattern, if it finds that MSB=1, into an entirely different bit-pattern. Since the MSB is simply "one of the 32 bits which comprises the value," it is dead-wrong to do anything to it which assumes that it's a sign-bit. And you also want to take care that it never gets displayed as a negative number, because it isn't. This quantity is 32 bits long, not 31+sign. Be sure it always looks that way.

Can a number in JavaScript ever reach to Infinity in runtime?

I was just curious, whether a number in JavaScript can ever reach Infinity.
The range of JavaScript numbers is pretty good enough -- 2 to the power of 64 different numbers, which is about 18 Quintilian (an 18 with 18 zeros after it). That’s a lot.
Now, I've few questions here:
What would really happen when a number grows beyond that range? Would JavaScript refer it as a new Infinity number?
What are all the scenarios in JavaScript, where the value Infinity could be assigned to a variable in runtime?
Let's look at a code example,
Attempting to write a method incrementNumToInfinity() to increment value of a certain number of times, so that a === b can evaluate to be true (also, to look at other possible scenarios, where the JavaScript Engine could assign the value Infinity to a variable in runtime).
var a = 1000; // a positive number
var b = Infinity;
console.log(a === b); // It returns false, that's expected
function incrementNumToInfinity(num) {
// Logic to convert our variable num into Infinity
return num;
};
a = incrementNumToInfinity(a); // Input: 1000, Expected output: Infinity
console.log(a === b); // Should return true
Can a number in JavaScript ever reach to Infinity in runtime?
It is possible at run time to get a number which is the result of a computation and which has for value Infinity. Nina Scholz has shown one such case: if you do x = 1 / 0, x will have for value Infinity.
What would really happen when a number grows beyond that range [i.e beyond the range JavaScript can handle]? Would JavaScript refer it as a new Infinity number?
We can try it. Number.MAX_VALUE is the maximum floating point number that JavaScript can represent. If you run this:
Number.MAX_VALUE + 1
You get a big number but not Infinity. What's going on there? Hmm, on a hunch let's try this:
Number.MAX_VALUE + 1 === Number.MAX_VALUE
The result is true. Say yhat? The problem is that floating point numbers have a limited precision, when I add 1 to Number.MAX_VALUE there isn't enough precision to register the increment.
If you try this:
Number.MAX_VALUE * 2
Then you get Infinity.
What are all the scenarios in JavaScript, where the value Infinity could be assigned to a variable in runtime?
"all the scenarios"... hmm... There are multiple issues with producing an enumeration of all the scenarios. For one thing, it is not clear what criteria should distinguish one scenario from one another. Is -Math.log(0) a different scenario from 1 / 0. If so, why? Then there's the issue that JavaScript engines have quite a bit of leeway to implement math functions. For instance, Math.tan is specified like this in the current draft:
Math.tan(x)
Returns an implementation-dependent approximation to the tangent of x. The argument is expressed in radians.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞ or -∞, the result is NaN.
It does not mandate a value for Math.tan(Math.PI / 2) If you recall your trigonometry classes, pi / 2 is 90 degrees and at that angle the tangent is infinite. Various versions of v8 have returned Infinity or a very large positive number. (See this question.) The specification does not mandate one result over the other: implementations are free to choose.
So practically if you start with a set of cases that you know mathematically should produce Infinity, you don't know whether they will actually produce that until you try them.
The part of your question with the incrementNumToInfinity function is not completely clear to me. You seem to be asking whether you can reach infinity simply by incrementing a number. It depends on what you mean. If you mean this:
let x = 0;
while (x !== Infinity) {
x++;
}
This will never terminate. x won't ever reach beyond Number.MAX_SAFE_INTEGER + 1. So it won't reach Infinity. Try this:
let x = Number.MAX_SAFE_INTEGER + 1;
x === x + 1;
You'll get the result true. That's again running into precision problems. The increment of 1 is not big enough to make a difference within the precision available to you.
Changing the increment to 2, 5, 10 or 10000000 does not really fix the issue, it just changes how far you can go before your increment no longer makes any difference.
Can a number in JavaScript ever reach to Infinity in runtime?
Assume your program does not have memory leak. I believe it can reach Infinity.
console.log(Number.MAX_SAFE_INTEGER)
// 9007199254740991
console.log(Number.MAX_VALUE)
// 1.7976931348623157e+308
var i = Number.MAX_SAFE_INTEGER
while (i != Infinity) {
i += Math.pow(10, 307)
console.log(i)
}
// 1.0000000000000005e+307
// 2.000000000000001e+307
// 3.0000000000000013e+307
// 4.000000000000002e+307
// 5.000000000000002e+307
// 6.000000000000003e+307
// 7.000000000000003e+307
// 8.000000000000004e+307
// 9.000000000000004e+307
// 1.0000000000000004e+308
// 1.1000000000000004e+308
// 1.2000000000000003e+308
// 1.3000000000000003e+308
// 1.4000000000000003e+308
// 1.5000000000000002e+308
// 1.6000000000000002e+308
// 1.7000000000000001e+308
// Infinity
The ratio of the square root of a square multiplied by PI of the same square subtracting PI to account for infinite decay as it approaches infinity, equals infinity. Or proving Archimedes wrong and right at the same time. PI and square are equivalent because neither will ever reach 0. This phenomenon also explains the zero boundary in the Pythagorean theory where A squared + B squared = c squared while approaching infinity.
Math.sqrt(1) / (Math.PI * ((Math.sqrt(1))) - Math.PI)
This is in result to the Fox and Duck Riddle. As the duck moves 1r of the distance to the pond the fox moves 180deg or the sum equivalent of the squares of its opposing and adjacent angles, we are give the square 2^2 (the travel distance from the center of the pond) Square root PI to the given 1:4 ratio therefor the hypotonuse of the triangle over pi - pi = Infinity or a 1:1 relationship with opposing vectors at any specific point.
ad 2:
What are all the scenarios in JavaScript, where the value Infinity could be assigned to a variable in runtime?
You could take a division with zero.
var x = 1 / 0;
console.log(x);

Bitwise operators stop working after 2^31

Say I have this:
// different things you can do
var CAN_EAT = 1,
CAN_SLEEP = 2,
CAN_PLAY = 4,
CAN_DANCE = 8,
CAN_SWIM = 16,
CAN_RUN = 32,
CAN_JUMP = 64,
CAN_FLY = 128,
CAN_KILL = 256,
CAN_BE_JESUS = Math.pow(2, 70);
// the permissions that I have
var MY_PERMS = CAN_EAT | CAN_SLEEP | CAN_PLAY | CAN_BE_JESUS;
// can I eat?
if(MY_PERMS & CAN_EAT) alert('You can eat!'); /* RUNS */
// can I sleep?
if(MY_PERMS & CAN_SLEEP) alert('You can sleep!'); /* RUNS */
// can I play?
if(MY_PERMS & CAN_PLAY) alert('You can play!'); /* RUNS */
// can I be jesus?
if(MY_PERMS & CAN_BE_JESUS) alert('You can be jesus!'); /* WONT RUN */
Then if I run it, it will print out that I can eat, sleep and play. It will not print out that I can be jesus, because that number is 2^70. If I make the number 2^31 then it will work (I'm on a 64bit machine but must be running Chrome in 32bit mode when I ran the above example).
I face this problem in PHP all the time as well, when dealing with bitwise operators. Often I can work the scenario I'm in to make it so having a maximum of 31 or 63 things in my list isn't a big deal, but sometimes I need to have much more than that. Is there any way around this limitation? Bitwise operators are so speedy, and convenient.
Well, the problem with this is apparently, as you suspected, the width of the integer in javascript. According to this, numbers in js can go up to 2^53, so you can have 53 different bits. According to this, in 64-bit machines, php goes all the way up to 2^63 - 1, so you get 62 bits.
If you need more, you should re-think your design - could you perhaps divide the flags into 2 (or more) groups, where each group has its own meaning (like food-related actions, other actions, anything else, etc.)?
You can read more about it in the ECMAScript Language Specification, ECMAScript is a subset of JavaScript, check here and here.
` Some ECMAScript operators deal only with integers in the range -2^31
through 2^31 - 1, inclusive, or in the range 0 through 2^32-1, inclusive.
These operators accept any value of the Number type but first convert
each such value to one of 2^32 integer values.
See the descriptions of the ToInt32 and ToUint32 operators in 9.5 and
9.6, respectively. `

Is there a better way of writing v = (v == 0 ? 1 : 0); [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I want to toggle a variable between 0 and 1. If it's 0 I want to set it to 1, else if it's 1 I want to set it to 0.
This is such a fundamental operation that I write so often I'd like to investigate the shortest, clearest possible way of doing it. Here's my best so far:
v = (v == 0 ? 1 : 0);
Can you improve on this?
Edit: the question is asking how to write the above statement in the fewest characters while retaining clarity - how is this 'not a real question'? This wasn't intended to be a code-golf exercise, though some interesting answers have come out of people approaching it as golf - it's nice to see golf being used in a constructive and thought-provoking manner.
You can simply use:
v = 1 - v;
This of course assumes that the variable is initialised properly, i.e. that it only has the value 0 or 1.
Another method that is shorter but uses a less common operator:
v ^= 1;
Edit:
To be clear; I never approached this question as code golf, just to find a short way of doing the task without using any obscuring tricks like side effects of operators.
Since 0 is a false value and 1 is a true value.
v = (v ? 0 : 1);
If you are happy to use true and false instead of numbers
v = !v;
or if they must be numbers:
v = +!v; /* Boolean invert v then cast back to a Number */
v = (v + 1) % 2 and if you need to cycle through more values just change 2 for (n + 1). Say you need to cycle 0,1,2 just do v = (v + 1) % 3.
You could write a function for it and use it like:
v = inv(v)
If you don't care about any possibility other than 1:
v = v ? 0 : 1;
In the above case, v will end up being 1 if v is 0, false, undefined or null. Take care using this kind of approach - v will be 0 even if v is "hello world".
Lines like v = 1 - v, or v ^= 1 or v= +!v will all get the job done, but they constitute what I would refer to as hacks. These are not beautiful lines of code, but cheap tricks to have the intended effect. 1 - v does not communicate "toggle the value between 0 and 1". This makes your code less expressive and introduces a place (albeit a small one) where another developer will have to parse your code.
Having instead a function like v = toggle(v) communicates the intent at the quickest glance.
(Honesty and mathematical integrity - given the number of votes on this "answer" - have led me to edit this answer. I held off as long as possible because it was intended as a short quip and not as anything "deep" so putting in any explanation seemed counter to the purpose. However, the comments are making it clear that I should be clear to avoid misunderstanding.)
My original answer:
The wording of this part of the specification:
If it's 0, I want to set it to 1, else set it to 0.
implies that the most accurate solution is:
v = dirac_delta(0,v)
First, the confession: I did get my delta functions confused. The Kronecker delta would have been slightly more appropriate, but not by much as I wanted something that was domain-independent (the Kronecker delta is mainly used just for integers). But I really shouldn't have used delta functions at all, I should have said:
v = characteristic_function({0},v)
Let me clarify. Recall that a function is a triple, (X,Y,f), where X and Y are sets (called the domain and codomain respectively) and f is a rule that assigns an element of Y to each element of X. We often write the triple (X,Y,f) as f: X &rightarrow; Y. Given a subset of X, say A, there is a characteristic function which is a function χA: X &rightarrow; {0,1} (it can also be thought of as a function to a larger codomain such as &Nopf; or &Ropf;). This function is defined by the rule:
χA(x) = 1 if x &in; A and χA(x) = 0 if x ∉ A.
If you like truth tables, it's the truth table for the question "Is the element x of X an element of the subset A?".
So from this definition, it's clear that the characteristic function is what is needed here, with X some big set containing 0 and A = {0}. That's what I should have written.
And so to delta functions. For this, we need to know about integration. Either you already know it, or you don't. If you don't, nothing I can say here will tell you about the intricacies of the theory, but I can give a one sentence summary. A measure on a set X is in essence "that which is needed to make averages work". That is to say that if we have a set X and a measure μ on that set then there is a class of functions X &rightarrow; &Ropf;, called measurable functions for which the expression ∫X f dμ makes sense and is, in some vague sense, the "average" of f over X.
Given a measure on a set, one can define a "measure" for subsets of that set. This is done by assigning to a subset the integral of its characteristic function (assuming that this is a measurable function). This can be infinite, or undefined (the two are subtly different).
There are lots of measures around, but there are two that are important here. One is the standard measure on the real line, &Ropf;. For this measure, then ∫&Ropf; f dμ is pretty much what you get taught in school (is calculus still taught in schools?): sum up little rectangles and take smaller and smaller widths. In this measure, the measure of an interval is its width. The measure of a point is 0.
Another important measure, which works on any set, is called the point measure. It is defined so that the integral of a function is the sum of its values:
∫X f dμ = ∑x &in;X f(x)
This measure assigns to each singleton set the measure 1. This means that a subset has finite measure if and only if it is itself finite. And very few functions have finite integral. If a function has a finite integral, it must be non-zero only on a countable number of points. So the vast majority of functions that you probably know do not have finite integral under this measure.
And now to delta functions. Let's take a very broad definition. We have a measurable space (X,μ) (so that's a set with a measure on it) and an element a &in; X. We "define" the delta function (depending on a) to be the "function" δa: X &rightarrow; &Ropf; with the property that δa(x) = 0 if x ≠ a and ∫X δa dμ = 1.
The most important fact about this to get a-hold of is this: The delta function need not be a function. It is not properly defined: I have not said what δa(a) is.
What you do at this point depends on who you are. The world here divides in to two categories. If you are a mathematician, you say the following:
Okay, so the delta function might not be defined. Let's look at its hypothetical properties and see if we can find a proper home for it where it is defined. We can do that, and we end up with distributions. These are not (necessarily) functions, but are things that behave a little like functions, and often we can work with them as if they were functions; but there are certain things that they don't have (such as "values") so we need to be careful.
If you are not a mathematician, you say the following:
Okay, so the delta function might not be properly defined. Who says so? A bunch of mathematicians? Ignore them! What do they know?
Having now offended my audience, I shall continue.
The dirac delta is usually taken to be the delta function of a point (often 0) in the real line with its standard measure. So those who are complaining in the comments about me not knowing my deltas are doing so because they are using this definition. To them, I apologise: although I can wriggle out of that by using the Mathematician's defence (as popularised by Humpty Dumpty: simply redefine everything so that it is correct), it is bad form to use a standard term to mean something different.
But there is a delta function which does do what I want it to do and it is that which I need here. If I take a point measure on a set X then there is a genuine function δa : X &rightarrow; &Ropf; which satisfies the criteria for a delta function. This is because we are looking for a function X &rightarrow; &Ropf; which is zero except at a and such that the sum of all of its values is 1. Such a function is simple: the only missing piece of information is its value at a, and to get the sum to be 1 we just assign it the value 1. This is none other than the characteristic function on {a}. Then:
∫X δa dμ = ∑x &in; X δa(x) = δa(a) = 1.
So in this case, for a singleton set, the characteristic function and the delta function agree.
In conclusion, there are three families of "functions" here:
The characteristic functions of singleton sets,
The delta functions,
The Kronecker delta functions.
The second of these is the most general as any of the others is an example of it when using the point measure. But the first and third have the advantage that they are always genuine functions. The third is actually a special case of the first, for a particular family of domains (integers, or some subset thereof).
So, finally, when I originally wrote the answer I wasn't thinking properly (I wouldn't go so far as to say that I was confused, as I hope I've just demonstrated I do know what I'm talking about when I actually think first, I just didn't think very much). The usual meaning of the dirac delta is not what is wanted here, but one of the points of my answer was that the input domain was not defined so the Kronecker delta would also not have been right. Thus the best mathematical answer (which I was aiming for) would have been the characteristic function.
I hope that that is all clear; and I also hope that I never have to write a mathematical piece again using HTML entities instead of TeX macros!
in general whenever you need to toggle between two values , you can just subtract the current value from the sum of the two toggle values :
0,1 -> v = 1 - v
1,2 -> v = 3 - v
4,5 -> v = 9 - v
You could do
v = Math.abs(--v);
The decrement sets the value to 0 or -1, and then the Math.abs converts -1 to +1.
If it must be the integer 1 or 0, then the way you're doing it is fine, though parentheses aren't needed. If these a are to be used as booleans, then you can just do:
v = !v;
v = v == 0 ? 1 : 0;
Is enough !
List of solutions
There are three solutions I would like to propose. All of them convert any value to 0 (if 1, true etc.) or 1 (if 0, false, null etc.):
v = 1*!v
v = +!v
v = ~~!v
and one additional, already mentioned, but clever and fast (although works only for 0s and 1s):
v = 1-v
Solution 1
You can use the following solution:
v = 1*!v
This will first convert the integer to the opposite boolean (0 to True and any other value to False), then will treat it as integer when multiplying by 1. As a result 0 will be converted to 1 and any other value to 0.
As a proof see this jsfiddle and provide any values you wish to test: jsfiddle.net/rH3g5/
The results are as follows:
-123 will convert to integer 0,
-10 will convert to integer 0,
-1 will convert to integer 0,
0 will convert to integer 1,
1 will convert to integer 0,
2 will convert to integer 0,
60 will convert to integer 0,
Solution 2
As mblase75 noted, jAndy had some other solution that works as mine:
v = +!v
It also first makes boolean from the original value, but uses + instead of 1* to convert it into integer. The result is exactly the same, but the notation is shorter.
Solution 3
The another approach is to use ~~ operator:
v = ~~!v
It is pretty uncommon and always converts to integer from boolean.
To sum up another answer, a comment and my own opinion, I suggest combining two things:
Use a function for the toggle
Inside this function use a more readable implementation
Here is the function which you could place in a library or maybe wrap it in a Plugin for another Javascript Framework.
function inv(i) {
if (i == 0) {
return 1
} else {
return 0;
}
}
And the usage is simply:
v = inv(v);
The advantages are:
No code Duplication
If you or anybody read this again in the future, you will understand your code in a minimum of time.
This is missing:
v = [1, 0][v];
It works as round robin as well:
v = [2, 0, 1][v]; // 0 2 1 0 ...
v = [1, 2, 0][v]; // 0 1 2 0 ...
v = [1, 2, 3, 4, 5, 0][v]; // 0 1 2 3 4 5 ...
v = [5, 0, 1, 2, 3, 4][v]; // 0 5 4 3 2 1 0 ...
Or
v = {0: 1, 1: 0}[v];
The charme of the last solution, it works with all other values as well.
v = {777: 'seven', 'seven': 777}[v];
For a very special case, like to get a (changing) value and undefined, this pattern may be helpful:
v = { undefined: someValue }[v]; // undefined someValue undefined someValue undefined ...
I don't know why you want to build your own booleans? I like the funky syntaxes, but why not write understandable code?
This is not the shortest/fastest, but the most clearest (and readable for everyone) is using the well-known if/else state:
if (v === 0)
{
v = 1;
}
else
{
v = 0;
}
If you want to be really clear, you should use booleans instead of numbers for this. They are fast enough for most cases. With booleans, you could just use this syntax, which will win in shortness:
v = !v;
Another form of your original solution:
v = Number(v == 0);
EDIT: Thanks TehShrike and Guffa for pointing out the error in my original solution.
I would make it more explicit.
What does v mean?
For example when v is some state. Create an object Status. In DDD an value object.
Implement the logic in this value object. Then you can write your code in a more functional way which is more readable. Switching status can be done by creating a new Status based on the current status. Your if statement / logic is then encapsulated in your object, which you can unittest. An valueObject is always immutable, so it has no identity. So for changing it's value you have to create a new one.
Example:
public class Status
{
private readonly int _actualValue;
public Status(int value)
{
_actualValue = value;
}
public Status(Status status)
{
_actualValue = status._actualValue == 0 ? 1 : 0;
}
//some equals method to compare two Status objects
}
var status = new Status(0);
Status = new Status(status);
Since this is JavaScript, we can use the unary + to convert to int:
v = +!v;
This will logical NOT the value of v (giving true if v == 0 or false if v == 1). Then we convert the returned boolean value into its corresponding integer representation.
Another way to do it:
v = ~(v|-v) >>> 31;
One more:
v=++v%2
(in C it would be simple ++v%=2)
ps. Yeah, I know it's double assignment, but this is just raw rewrite of C's method (which doesn't work as is, cause JS pre-increment operator dosen't return lvalue.
If you're guaranteed your input is either a 1 or a 0, then you could use:
v = 2+~v;
Just for kicks: v = Math.pow(v-1,v) also toggles between 1 and 0.
define an array{1,0}, set v to v[v], therefore v with a value of 0 becomes 1, and vica versa.
Another creative way of doing it, with v being equal to any value, will always return 0 or 1
v = !!v^1;
If possible values for v are only 0 and 1, then for any integer x, the expression:
v = Math.pow((Math.pow(x, v) - x), v);
will toggle the value.
I know this is an ugly solution and the OP was not looking for this...but I was thinking about just another solution when I was in the loo :P
Untested, but if you're after a boolean I think var v = !v will work.
Reference: http://www.jackfranklin.co.uk/blog/2011/05/a-better-way-to-reverse-variables
v=!v;
will work for v=0 and v=1; and toggle the state;
If there are just two values, as in this case(0, 1), i believe it's wasteful to use int. Rather go for boolean and work in bits. I know I'm assuming but in case of toggle between two states boolean seems to be ideal choice.
v = Number(!v)
It will type cast the Inverted Boolean value to Number, which is the desired output.
Well, As we know that in javascript only that Boolean comparison will also give you expected result.
i.e. v = v == 0 is enough for that.
Below is the code for that:
var v = 0;
alert("if v is 0 output: " + (v == 0));
setTimeout(function() {
v = 1;
alert("if v is 1 Output: " + (v == 0));
}, 1000);
JSFiddle: https://jsfiddle.net/vikash2402/83zf2zz0/
Hoping this will help you :)

Categories