problem with JS comparison logic if/and/or - javascript

so here is the scenario
if ( ( a >= b) && ( (c < d) && (d != '') ) )
cannot get this logic on this to work correctly
so if d = '' it would cause that to be false. which would mean that the whole thing would equate to false. Problem is I need it to trigger when a >= b but also needs to include the and for c < d but only if d != '', in other words ignore the c < d part if d = '', otherwise used the c < d part to prevent a >= b from triggering.
hope this is making sense. I am trying to avoid doing and if/else or switch.

One comment would be if you are not absolutely avoid using if/else or switch then you could define funcitons use them and use thiss functions in your statement above.
Apart from that, changing the order of some expressions might do what you want. c < d would not be evaluated if d = '' is not true. a >= b would not be evaluated if the expresion before second or, ||, is true or d == '', empty string, is true.
if ((d != '' && c < d) || (d != '' && c >= d && a >= b))
which is;
if (d != '' && (c < d || a >= b))

thanks for your suggestions, I found a workaround though
I just put
if (d == '') { d = Infinity; }
then
if ( (a >= b) && (c < d) )
and that solved it
thanks for everyone's help

Related

Conditional logical operator using four variables

I have a function that returns a condition using four variables.
(payload, variables) => {
return payload.newMessage.lenderId === variables.lenderId && payload.newMessage.user.id === variables.authId
}
I want to be able to say C === D is only if C and D exists. What would be the optimal expression for this? So A === B is a sufficient condition if C and D doesn't exist, but if C and D exist, A === B and C === D both have to be met.
A and B must always be equal, and one of the following must be true:
There is no C
There is no D
C and D are equal
(A === B) && (!C || !D || C === D)
Beyond this construction, you should know what you mean by "exists" - is it enough that they not be undefined? Is it any truthy value? Etc.
function customCheck(a,b,c,d) {
const abComparison = a === b;
if (c && d) {
return abComparison && (c === d);
}
return abComparison;
}
From your description seems something like above?

How to simplify or statement

Is there a way to simplify this statement to be a 'prettier' comparison:
a <= 1 ||
b <= 1 ||
d <= 1 ||
!c;
You could put a, b, and d in an array, and check whether some of them are <= 1:
[a, b, d].some(num => num <= 1) || !c

x >= x pattern in JavaScript

When reading source of D3.js I saw x >= x pattern. If it is for detecting NaNs among numbers, why not just isNaN(x) or x == x?
Source, where I encountered it:
d3.min = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n) if ((b = array[i]) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = array[i]) != null && a > b) a = b;
} else {
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
}
return a;
};
From my investigations, d3.min is supposed to work on any kind of orderable values, not only numbers. isNaN would only work numbers.
d3 was actually using == at some point. This commit introduced the x == x test:
Unlike Math.min and Math.max, it doesn't make sense to return negative or positive infinity for d3.min and d3.max; the D3 functions return the minimum value according to an arbitrary ordering, not by numeric value. Instead, the minimum or maximum of an empty array, or an array that contains only degenerate values, should always be undefined.
This commit changed x == x to x <= x (which was later again changed to x >= x):
In addition to NaN, which is not equal to itself, you can have objects that are not orderable due to defined valueOf functions which return NaN. For example:
var o = new Number(NaN);
Here, o == o is true, but o <= o is false. Therefore it was possible for d3.min, d3.max and d3.extent to observe these non-orderable values rather than ignore them as intended. The fix is to check !(o <= o) rather than o == o.
OK, I see that x >= x gives false for both NaN and undefined. (Unlike isNaN(x) or x == x.)
EDIT: While it is one of the use cases of x >= x, in this case (thx #Felix Kling for pointing this out) undefined is already being checked.

Javascript comma syntax, and complex expressions, minified, obfuscated: please help me understand a piece of code

I need to understand some pieces of code. I feel fine with the syntax of Java, C++, PHP, but Javascript syntax is still a "dark forest" for me. Here are the original forms and possible interpretations, I mean equivalents in terms of program logic:
1.
var o,
a,
s = "https://widget.kiwitaxi.com",
c = e.createElement("iframe"),
l = e.getElementById(r.target),
p = r && r.height_bias ? 4 + r.height_bias : 4,
u = !1,
f = parseInt(r.min_height, 10) ? parseInt(r.min_height, 10) : r.hide_form_extras && !r.default_form_title ? 304 : 386;
I'm almost sure about this one, here I can replace commas with semicolons and add VAR statement to the beginning of each line and it will produce the same results, am I right?
var o;
var a;
var s = "https://widget.kiwitaxi.com";
var c = e.createElement("iframe");
var l = e.getElementById(r.target);
var p = r && r.height_bias ? 4 + r.height_bias : 4;
var u = !1;
var f = parseInt(r.min_height, 10) ? parseInt(r.min_height, 10) : r.hide_form_extras && !r.default_form_title ? 304 : 386;
And this one is really tough for me, I cannot presume any interpretation
As I understand:
"o" is evaluated to s + "/w", then is concatenated with "-", and then with ".html" ? Are any conditions applied to that string building, I mean, can any of that two concatenations be applied by condition in this code ?
What does comparison == operator do in the statement (the part "en" == r.language...), which variable receives that result ? Or can it be just an obfuscation trick ?
And the last one, after the last comma, r.banner_id || (r.banner_id = "22995c4e"); Here goes an assignment, that is clear, but what is the point of other stuff in this part ? Is the assignment made by condition here (if r.banner is not undefined-or-null-or-false) ?
o = s + "/w",
"en" == r.language && (o += "-" + r.language.toString().toLowerCase()),
("biletik" == r.theme || "ostrovok" == r.theme) &&
(o += "-" + r.theme.toString().toLowerCase()),
o += ".html",
r.banner_id || (r.banner_id = "22995c4e");
"en" == r.language && (o += "-" + r.language.toString().toLowerCase()),
Ooh...that line's tricky.
So, example: If you were to write var myVar = false && thisFunctionThrowsError(), where the function would throw an exception if it were called, that would actually not return an error - because anything after the ampersand won't be evaluated. It's called short-circuit evaluation. In this case, someone has cut out the part where he checks the result of the && comparison, and only uses it to determine whether or not to run the right side.
So, if I write:
"biletik" == r.theme && (o += "-");
That means it will add a dash to o only if r.theme == 'biletik'.
The last line is the opposite; it looks like it's a lazy-initializer. If r.banner_id is null, that evaluates to false - so it runs the second part of the ||, initializing it to 22995c4e.

How to trim document.getElementbyId value in JavaScript? [duplicate]

JavaScript doesn't seem to have a native trim() method. How can I trim white spaces at the start and end of a string with JavaScript?
The shortest form for jQuery:
string = $.trim(string);
Link
according to this page the best all-around approach is
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
Of course if you are using jQuery , it will provide you with an optimized trim method.
I know this question is ancient but now, Javascript actually does have a native .trim()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
Well, as a lot of people always says, the trim function works pretty well, but if you don't want to use a whole framework just to perform a trim, it may be useful to take a look at its implementation. So here it is:
function( text ) { return (text || "").replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" );}
The main advantages I see in this implementation, comparing to other solution already proposed here are:
The 'g' flag that allows you to perfom a trim on a multi-line string
The (text || "") syntax that ensure that the function will always work, even if the argument passed is null or undefined.
As a couple of others have already noted, it's usually best to do this sort of thing by using a third-party JS library. Not that trim() is a complicated function to build yourself, but there are so many functions that aren't native to JavaScript that you might need and end-up writing yourself, it soon becomes more cost-effective to use a library.
Of course, another advantage of using a JS library is that the authors do the hard work of ensuring that the functions work across all the major browsers, so that you can code to a standard interface and forget about the irritating differences between Internet Explorer and all the other browsers.
A slightly tinier version of #Pat's.
return str.replace( /^\s+|\s+$/g, '' );
For ltrim, replace spaces anchored at the start of the string with nothing:
str2 = str.replace(/^\s+/,'');
For rtrim, replace spaces anchored at the end of the string with nothing:
str2 = str.replace(/\s+$/,'');
For trim:
str2 = str.replace(/^\s+|\s+$/g,'');
These all use regex'es to do the actual work.
Why not just modify the String prototype? Why not steal the trim function from an open source library, like I did here with YUI? (Do you really need to load and entire framework for this simple taks?) Put them together and you get this:
String.prototype.trim = function() {
try {
return this.replace(/^\s+|\s+$/g, "");
} catch(e) {
return this;
}
}
var s = " hello ";
alert(s.trim() == "hello"); // displays true
Use Ariel Flesler's fast trim function:
// Licensed under BSD
function myBestTrim( str ){
var start = -1,
end = str.length;
while( str.charCodeAt(--end) < 33 );
while( str.charCodeAt(++start) < 33 );
return str.slice( start, end + 1 );
};
My solution, though, would be this (because the String object in Firefox 3.5 and above already has a trim method):
String.prototype.trim = String.prototype.trim || function () {
var start = -1,
end = this.length;
while( this.charCodeAt(--end) < 33 );
while( this.charCodeAt(++start) < 33 );
return this.slice( start, end + 1 );
};
I made a trim-function speed in mind. This function beats in a clear difference all of 24 competitors (of which many use regular expressions) and also native string.trim() of Chrome and Chromium(!) and performs as speedy as Safari's trim(). Test results are here: http://jsperf.com/mega-trim-test/7
function trim27(str) {
var c;
for (var i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)
continue; else break;
}
for (var j = str.length - 1; j >= i; j--) {
c = str.charCodeAt(j);
if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)
continue; else break;
}
return str.substring(i, j + 1);
}
The function trims characters " \n\r\t\f", but it's easy to add more whitespace-characters, eg. those that regexp uses as whitespaces (\s) with only a minor performance lost ( please see http://jsperf.com/mega-trim-test/8 ).
Edit: The previous trim27() trims only the most common characters (" \n\r\t\f"), but to trim all possible whitespaces, I included below a new function mytrim():
if (!String.prototype.trim || "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF".trim() || navigator.userAgent.toString().toLowerCase().indexOf("chrome") != -1)
var mytrim = function(str) {
var c;
for (var i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)
continue; else break;
}
for (var j = str.length - 1; j >= i; j--) {
c = str.charCodeAt(j);
if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)
continue; else break;
}
return str.substring(i, j + 1);
};
else var mytrim = function(str) {
return str.trim();
}
Use it this way:
var foo = mytrim(" \n \t Trimmed \f \n "); // foo is now "Trimmed"
The above mytrim() does the following:
Trims 26 different whitespaces (all of 25 whitespaces mentioned in http://perfectionkills.com/whitespace-deviations/ and additionally uFEFF, which is ZERO WIDTH NO-BREAK SPACE.
Makes trimming results consistent across browsers.
Uses native trim() if it is available AND has ability to trim all of 27 different whitespaces. The exception is Chrome and Chromium which both have so slow native trim() that instead of native we use our custom trim.
AND THE MOST IMPORTANT: Is not beautiful and is not short, but IS CLEARLY FASTER than any of the 24 competitive alternatives in http://jsperf.com/mega-trim-test/12 (exception: rather old Firefox 3.6.25 in Windows 7 runs mytrim() rather slowly for unknown reason).
I use this with native JavaScript
// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
Use like this
var myString = " some text ";
alert(myString.trim());
Example
// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
var str = " some text ";
console.log(str.trim());
The answer to so many JavaScript questions: jQuery
$j.trim(string)
Note: the above assumes your jQuery has been setup with:
<script type="text/javascript">$j = jQuery.noConflict();</script>
Which is far more sensible than "$", and far less verbose than typing "jQuery" every time.
Microsoft .NET also has String.trim function as a part of JavaScript Base Type Extensions. It could be used if you are coding ASP.NET application.
I use this.
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
Actually, with jQuery this seems to be the way:
jQuery.trim(string)
(Reference)
I use this:
Work with functions.
function trim($) {
return (typeof $ == "function" ? $() : $).replace(/[\s]*/g,"")
}
code example:
trim((function(){ return "a b"})) // ab
trim(" a b") //ab
This is probably not the fastest, and might violate what ".trim()" probably should really be, but I don't like RegExs (mainly because it takes so much time to figure out what they really mean/do) and I like having something that I know will work regardless of whether I have jQuery or not (not to mention the right version, since I tried $.trim(myVar) with jQuery 1.4.2 and it does not work), and will get rid of ALL extra spaces, not just at the end, rebuilding it like it should be:
function Trim(obj) {
var coll = "";
var arrObj = obj.split(' ');
for (var i=0;i<arrObj.length;i++) {
if (arrObj[i] == "") {
arrObj.splice(i,1); // removes array indices containing spaces
}
}
//alert(arrObj.length); // should be equal to the number of words
// Rebuilds with spaces in-between words, but without spaces at the end
for (var i=0;i<arrObj.length;i++) {
if (arrObj[i] != "" && i != arrObj.length-1)
coll += arrObj[i] + " ";
if (arrObj[i] != "" && i == arrObj.length-1)
coll += arrObj[i];
}
return coll;
}
This is an old question but none of these worked for me. I just needed to trim leading and trailing white space and this is what I did. My div tag had an id = start-date.
$("#start-date").text().trim()
You can use following ...
function trim(str) {
try {
if (str && typeof(str) == 'string') {
return str.replace(/^\s*|\s*$/g, "");
} else {
return '';
}
} catch (e) {
return str;
}
}

Categories