How to short the expression? - javascript

I have that expression
if (a === Infinity && b === 0 || a === -Infinity && b === 0 || a === 0 && b === Infinity || a === 0 && b === -Infinity) {
return NaN
}
I want short it, but I have no idea how to do this
UPDATE
If it possible, I cant use isFinite(), how to shorten else?

You can use !isFinite() to test if it's either Infinity or -Infinity.
if ((!isFinite(a) && b === 0) || (!isFinite(b) && a === 0)) {
return NaN;
}

If a and b are number typed, then:
if (!(a*b || isFinite(a+b))) return NaN;
If your linter warns about use of global functions, then:
if (!(a*b || Number.isFinite(a+b))) return NaN;
If you can't use multiplication:
if (!(a && b || Number.isFinite(a+b))) return NaN;

Math.absing both and then checking that the minimum is 0 and the maximum is infinity should do it.
const nums = [a, b].map(Math.abs);
if (Math.min(...nums) === 0 && Math.max(...nums) === Infinity) {
return NaN;
}
Can also sort the array.
const nums = [a, b]
.map(Math.abs)
.sort(a, b) => a - b); // .sort() works too, but could be more confusing
if (nums[0] === 0 && nums[1] === Infinity)) {
return NaN;
}

Related

Ternary operator inside if condition not transpiled properly using babel

let a = null, b = null;
if ((a !== null) && a.active && ((a === null) ? (a === b) : true)) {
}
After babel transpile above condition is transformed into
if (a !== null && a.active && a === null ? a === b : true) {
}
and it is always returning true because ternary operator has less precedency than comparison operators
any solution not to omit parentheses in this kind of conditions?

Is there a way to know the value of a variable in an if statement without knowing what the variable is?

I am trying to find out the value of the second variable in the if statement without knowing what the variable is.
EX:
//a, b, and c are controlled by the user in input boxes.
let a = "Josh"
let b = "James"
let c = ""
if (a.length!== 0 && b.length !== 0|| a.length !== 0 && c.length !== 0){
Here I want to check if a equals the value that the length doesn't equal 0. In this case b.
Ex:
if (a == secondVariable){
alert("WOOH")
}
I know I can write
if (a.length !== 0 && b.length !== 0){
if (a == b){
alert("WOOH")
}
} else if (a.length !== 0 && c.length !== 0){
if (a == c){
alert("BOOH")
}
} else {
alert("")
}
But this is a lot of code and I have a lot more variables to check in my code. Is there a more efficient way to write this? Thank you
You can combine the ifs. Also you only need to check the length of one thing if you are also comparing it vs other thing. Also there is a shortcut coercing the length property to a boolean:
if (a.length && a == b) {
alert("WOOH");
}
if (a.length && a == c) {
alert("BOOH");
}

Programming logic - Compare 3 values - JS

I have this snippet that is is getting 3 numbers and its working distinguing them. If one of 3 numbers is diferent than the others it must return its correspondend.
An input example:
1 1 0
0 0 0
1 0 0
output must be:
C
*
A
The approach i had was that one:
var input = require('fs').readFileSync('stdin', 'utf8')
var lines = input.split('\n')
for (let i = 0; i < lines.length; i++) {
var round = lines[i].split(' ').map(i => parseInt(i))
// console.log(round); [1, 1, 0]
var A = round[0]
var B = round[1]
var C = round[2]
if(A === B && A === C){
console.log("*");
} else if (A === B && A !== C) {
console.log("C");
} else if (A !== B && A === C) {
console.log("B");
} else if (A !== B && A !== C) {
console.log("A");
}
}
I'm not sure what the problem is exactly but if it is to try to minimize the code in some way one thing to notice is that we don't care whether the the values are 0 or 1 only whether the players have chosen the same or not so once we have the values of A, B and C for a round we can just do:
(UPDATE: thanks to a comment from #Samathingamajig a redundant != comparison has been removed)
console.log( ((A==B)&&(B==C)) ? '*' : (A==B) ? 'C' : (A==C) ? 'B' : 'A' );
Like #Samathingamajig said:
function _0or1(arr) {
[A,B,C] = arr
if (A === B && A === C) {
console.log("*");
} else if (A === B) {
console.log("C");
} else if (A === C) {
console.log("B");
} else {
console.log("A");
}
}
_0or1([0,0,0])
_0or1([1,0,0])
_0or1([0,1,0])
_0or1([0,0,1])
_0or1([1,1,0])
_0or1([0,1,1])
_0or1([1,0,1])
_0or1([1,1,1])

handle empty strings at array.sort(?) callback in chrome is very slow

in js i have to sort a lot of array elements(100k-1kk).
İn production its possible to have many blank ('') strings.
in my sort function i handle empty values - so that this values always come last .its ok.. until i have many null or undefined or blank('') values in data
if data have many nulls for example or blank strings performance is veeery slow.
And the main thing is that this fragment very slow at Chrome (at least last version for now 49.0.2623.110 m)
firefox(45.0.1) works very well (even with standart case without empty data my test x10 faster ??)
just test.with chrome and firefox
P.S. i know jsperf is more preferable for that.anyway
https://jsfiddle.net/3h0gtLu2/18/
data = []
var i = 0;
while (i++ <1000){
data.push('' + i)
}
while (i++ < 20000){
data.push(''+i )
}
var start = window.performance.now()
data.sort(function(a,b){
if (a == null || a == undefined)
return 1;
else if ( b == null || b == undefined)
return -1;
return (parseInt(a) - parseInt(b));
})
$('#time0').html($('#time0').html() + (window.performance.now() - start))
data = []
var i = 0;
while (i++ <1000){
data.push('' + i)
}
while (i++ < 20000){
data.push(null )
}
var start = window.performance.now()
data.sort(function(a,b){
if (a == '' || a === null || a == undefined)
return 1;
else if ( a == '' || b === null || b == undefined)
return -1;
return (parseInt(a) - parseInt(b));
})
$('#time1').html($('#time1').html() + (window.performance.now() - start))
data = []
var i = 0;
while (i++ <1000){
data.push('' + i)
}
while (i++ < 20000){
data.push('' )
}
var start = window.performance.now()
data.sort(function(a,b){
if ( a == null || a == undefined)
return 1;
else if ( b == null || b == undefined)
return -1;
return (parseInt(a) - parseInt(b));
})
$('#time2').html($('#time2').html() +( window.performance.now() - start))
data = []
var i = 0;
while (i++ <1000){
data.push('' + i)
}
while (i++ < 20000){
data.push('' )
}
var start = window.performance.now()
data.sort(function(a,b){
if (a == '' || a == null || a == undefined)
return 1;
else if (b == '' || b == null || b == undefined)
return -1;
return (parseInt(a) - parseInt(b));
})
$('#time3').html($('#time3').html() +( window.performance.now() - start))
In order to ensure that your comparator will always return a logical answer for every pair of values, you'll have to add the case for when both values are empty:
data.sort(function(a,b){
var anull = (a == '' || a == null), bnull = (b == '' || b == null);
if (anull && bnull)
return 0;
if (anull)
return 1;
if (bnull)
return -1;
return (parseInt(a) - parseInt(b));
})
Note that you don't need an explicit compare to both null and undefined; comparing == null is exactly the same as comparing === null and === undefined.
My making sure you tell the sort algorithm that when both values are empty they can be left alone (by returning 0), you avoid it thrashing back and forth in some weird cases.
Another thing that might speed things up would be to make a single pass through the array to convert all the empty entries to some single value (maybe null; doesn't matter) and all the non-empty entries to actual numbers. That way your sort won't be paying the price of converting the strings to numbers over and over again (that is, all the calls to parseInt()). If you want the array to be strings, you can always convert it back in a subsequent single pass.

JavaScript short circuit evaluation error?

The two below snippets of JS code have had me confused, in my eyes both should work the same, due to short circuit evaluation. But for some reason snippet '1' causes the error (on the third line):
Cannot read property 'match' of undefined
Array 'a' holds 3 character values user entered into inputs. I want the code to return true if the char is undefined, an empty string, or a letter or number.
To be clear, this fails when a = ['a', '/'];
Snippet 1)
return typeof a[0] === 'undefined' || a[0] === '' || a[0].match(/^[a-z0-9]+$/i)
&& typeof a[1] === 'undefined' || a[1] === '' || a[1].match(/^[a-z0-9]+$/i)
&& typeof a[2] === 'undefined' || a[2] === '' || a[2].match(/^[a-z0-9]+$/i);
Snippet 2)
if (typeof a[0] === 'undefined' || a[0] === '' || a[0].match(/^[a-z0-9]+$/i)) {
if (typeof a[1] === 'undefined' || a[1] === '' || a[1].match(/^[a-z0-9]+$/i)) {
if (typeof a[2] === 'undefined' || a[2] === '' || a[2].match(/^[a-z0-9]+$/i)) {
return true;
}
return false;
}
return false;
}
return false;
Surely a[2].match should never be evaluated if a[2] is undefined due to the first conditional in the 'if'?
The answer is simple. Take a look to the order of operations .
AND binds more than OR.
In your Snippet 1 the expression is like:
a1 || b1 || (c1 && a2) || b2 || (c2 && a3) || b3 || c3
Your Snippet 2 is like:
(a1 || b1 || c1) && (a2 || b2 || c2) && (a3 || b3 || c3)
#Christoph is right but you also need to add something like !== null after match like
return (typeof a[0] === 'undefined' || a[0] === '' || a[0].match(/^[a-z0-9]+$/i) !==null ) && (typeof a[1] === 'undefined' || a[1] === '' || a[1].match(/^[a-z0-9]+$/i) !== null ) && (typeof a[2] === 'undefined' || a[2] === '' || a[2].match(/^[a-z0-9]+$/i) !== null);
You can take a look at this fiddle http://jsfiddle.net/dv360q1p/1/ which implements your question

Categories