Writing multiple logical operators more concisely - javascript

I'm trying to write multiple logical operators in a more concise way. In my case, I want the function to only run when all four inputs are only numbers. The only way I can think of doing this is to write them all in one if statement with &&, use multiple ifs (as below), or use switch. But I was wondering if there is a more concise way.
function fn() {
const input = display.getInput();
if (input.p !== "" && !isNaN(input.p)) {
if (input.d !== "" && !isNaN(input.d)) {
if (input.s !== "" && !isNaN(input.s)) {
if (input.y !== "" && !isNaN(input.y)) {
if (input.y <= 100) {
/* run code */
}
}
}
}
}
}

To answer exactly what you area asking, you could do it like this:
if (input.p !== "" && !isNaN(input.p) && input.d !== "" && !isNaN(input.d) ...
But in fact you should write it better. First implement a validation function:
function isValid(property) {
return property !== "" && !isNaN(property);
}
So the if would be like:
if (isValid(input.p) && isValid(input.d) && ...
And finally, you might want to put everything into a new function:
function isEverythingValid(input) {
for (let property of ["p", "d", "s", "y"]) {
if (!isValid(input[property])) {
return false;
}
}
return input.y <= 100;
}

Related

shorten if conditions in js

I want to shorten the conditions of a javascript if but I don't know how I can achieve it
code:
if ((!emailValidation() || (!nameValidation()) || (!surnameValidation()) || (!addressValidation()) || (!cityValidation()) || (!postalCodeValidation()))) {
}
I have the conditions defined in this way:
let surnameValidation = () => {
if (apellidoUsuario.value.length == 0) {
surnameError();
return false;
}
else if (apellidoUsuario.value.length == 1) {
surnameError();
return false;
}
else {
apellidoUsuario.focus;
apellidoUsuario.style.border = '0';
apellidoUsuario.style.backgroundColor = 'transparent';
apellidoUsuario.style.outline = '1px solid #00ffb1'
apellidoUsuario.style.transitionDuration = '0.4s'
return true;
}
I appreciate any help! :)
You can remove all unnecessary parenthesis in your if condition:
if (
!emailValidation() ||
!nameValidation() ||
!surnameValidation() ||
!addressValidation() ||
!cityValidation() ||
!postalCodeValidation()
) {
}
Other than that, there's not really a clean, readable way to shorten your code.
Proposition #1:
I would probably get those validations into a variable or function:
validations() {
return [
emailValidation(),
nameValidation(),
surnameValidation(),
addressValidation(),
cityValidation(),
postalCodeValidation()];
}
and then I would:
if(validations().some(x=> !x)){
...
}
since validations return an array you can just use the some operator to find any invalid value.
Proposition #2:
I particularly would:
valid() {
return [
emailValidation(),
nameValidation(),
surnameValidation(),
addressValidation(),
cityValidation(),
postalCodeValidation()].every(x => x === true);
}
and then I would:
if(!valid()){
...
}
It is always cleaner to use true conditions on if statements instead of false ones.
References: Clean Code - Uncle Bob.

simplify if-statement in Javascript

$scope.vergleich = function () {
if ($scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei ) !== -1) {
return true
} else {
return false; }
}
}
I am currently student and intelliJ tells me I have to simplify this if-statement but I have no idea how. Maybe somebody can help me.
The simplification is probably that, if condition is a boolean, :
if (condition) {
return true;
}
else {
return false;
}
is equivalent to
return condition;
However there also seems to be a logical error in your test.
$scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei ||
dataService.dic.neu.rechtsformKanlei ) !== -1
Does not mean the same thing as :
$scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei) !== -1 ||
$scope.relrechtsform.indexOf(dataService.dic.neu.rechtsformKanlei) !== -1
Maybe you're looking for this:
$scope.vergleich = function () {
return $scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei ) !== -1;
};
Tân's version is a correct answer to your question. However, with recent JavaScript you can simplify even more thanks to array.includes:
$scope.vergleich = () =>
$scope.relrechtsform.includes(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei)
You can just use your condition instead of using IF else statement -:
$scope.vergleich = function () {
return ($scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei ||
dataService.dic.neu.rechtsformKanlei ) !== -1);
};

How to check isEmpty in javascript

I want to check the response.data.totalRows is empty.
if (response!=undefined
&& response.data!=undefined
&& response.data.totalRows!=undefined) {
alert(response.data.totalRows);
}
Can simplify the code?
UPDATE: it seems that there is no simple method like isEmpty(response.data.totalRows).
Yea, you can simply do this:
if (response && response.data && response.data.totalRows) {
alert(response.data.totalRows);
}
In JavaScript, a object is cast to a truthy value, when used in a if. This means you can just "dump" the variable in a if or any other boolean statement, as a check to see whether or not it exists. this blog post has some more information about it.
Please note that this will not alert anything if totalRows equals 0 (since 0 is considered a falsy value.) If you also want to alert if it's 0, use this:
if (response && response.data &&
(response.data.totalRows || response.data.totalRows === 0)) {
alert(response.data.totalRows);
}
Or:
if (response && response.data && response.data.totalRows !== undefined) {
alert(response.data.totalRows);
}
Supposing that response.data.totalRows must be an array you can use just:
if (!response.data.totalRows.length) {
/* empty array */
}
If you are not sure that totalRows exists you must verify:
if (
!response ||
!response.data ||
!response.data.totalRows ||
!response.data.totalRows.length
) {
/* is empty */
}
Any value is converted in Boolean. For example: Boolean(response) will return false if response will be 0, null, undefined etc.
What about a try-catch block?
try{ alert(response.data.totalRows); }
catch(e) { alert("undefined"); }
I'd write a prototype (even if it's not recommended)
Object.prototype.isEmpty = function(){
return (!this || this===undefined || this===null || !this.hasChildNodes())
?true
:false;
}
And then just use
if(!response.isEmpty()) alert(response.data.totalRows);
It is only handy if you need the checks also elsewhere and not only one place.
Just
response && response.data && response.data.totalRows && alert(response.data.totalRows)
If the property list gets very long there is another syntax you can use, in the sample code I've created a function so it can be re used.
// args is { object: the object to check the properties of
// properties: an array of strings with property names}
function isSet(args){
//no checking of arguments
var o = args.object,
props = args.properties,
i = -1,len = props.length
while(typeof o !== "undefined"
&& o !== null
&& ++i<len){
o = o[props[i]];
}
return (typeof o !== "undefined"
&& o !== null)?true:false;
}
var test = {
prop1 : {
prop2 : "ok"
}
};
//check if test.prop1.prop2 is set
console.log(isSet({
object:test,
properties: ["prop1","prop2"]
}));//=true

Javascript statements all to be evaluated

Hi I want each if statements to be evaluated (java script). This is not happening, when one or two are true the remaining statements are not evaluated. They are all independent questions. What should I be using instead of if and else? Thanks.
//Side-Vent-Even
if (SideVent == "Side-Vent-Even" && Canvas=="Base-Shirt") {
// do this
}
//Side-Vent-Uneven
else if (SideVent2 == "Side-Vent-Uneven" && Canvas=="Base-Shirt") {
// do this
}
//Golf-Tee-Right
else if (GolfTee == "Golf-Tee-Right" && Canvas=="Base-Shirt") {
// do this
}
//Golf-Tee-Left
else if (GolfTee2 == "Golf-Tee-Left" && Canvas=="Base-Shirt") {
// do this
}
Turn them in to regular ifs, which will cause them all to be run independently of each other
if(){
}
....
if(){
}
If else are used when you wish to perform condition from either of them but not both or all, in your case you want all of them to be performed, hence use if condition statement for all, like
//Side-Vent-Even
if (SideVent == "Side-Vent-Even" && Canvas=="Base-Shirt") {
// do this
}
//Side-Vent-Uneven
if (SideVent2 == "Side-Vent-Uneven" && Canvas=="Base-Shirt") {
// do this
}

I am looking for a smart way to check the object parameter passed to a function

I am in the following situation:
I have to check if the object parameter passed to a function is valid:
Exmaple:
function (opt) {
if (opt && opt.key && opt.key2) {
// make something
}
}
Is there a better way to make this kind of check?
Not really.
Unless you can use opt.pleaseReadMyMind() ;-)
You could create a method that will check if all fields have values different to null, though.
That's the most compact way of doing it.
The most correct way would be:
if( typeof opt !== "undefined" && typeof opt.key !== "undefined" && typeof opt.key2 !== "undefined") {
But as you can see that's quite a mouthful and not really necessary.
Just write a simple test routine to verify the object given a list of property names:
// usage: testProps(object to test, [list, of, property, names])
// returns true if object contains all properties
function testProps(obj, props)
{
if (obj === null)
return false;
var i;
for (i=0; i<props.length; ++i)
{
if (!(props[i] in obj))
return false;
}
return true;
}
And then in your function:
if (!testProps(obj, ['key', 'key2'])
return;
What you are doing is valid, but it does have flaws.
if (opt && opt.key && opt.key2) {
This check would fail if opt.key has falsely values [0,null,false,and so on]
In that case you would have to do a typeof check to make sure it is not undefined.
if (opt && typeof opt.key !== "undefined" && opt.key2) {
Yeah, but it's only "better" if you have a lot of keys to check, not just three. Something like this:
function opt(opt) {
for(var i = 0; i<3; i++) {
if(typeof opt["key"+((i > 0) ? "" : i + 1))] === "undefined") {
return;
}
}
// create object
}
If opt is undefined all its keys will be too, so there's an implicit check for that as well.
You could also define the variable names you want to check in array, something like this:
var propsToCheck = ["key", "key1", "key2"];
function(opt) {
for(var i = 0, ii = propsToCheck.length; i<ii; i++) {
if(typeof opt[propsToCheck[i]] === "undefined") {
return;
}
// create object
}
}
Not really much of a better solution, but it does allow for less typing if you're planning on checking more than three or four properties.
You could always do it like this:
function validate(o, args) {
if (typeof(o) == 'object' && args instanceof Array) {
for (var i = args.length - 1; i >= 0; --i) {
if (typeof(o[args[i]]) === 'undefined') return false;
}
return true;
} else {
return false;
}
}
function myFunction(obj) {
if (validate(obj, ['foo', 'bar'])) {
// Your code goes here.
} else {
// Object passed to the function did not validate.
}
}
Here's a fiddle for you: http://jsfiddle.net/reL2g/

Categories

Resources