Instead of if...else statement how to do using ternary operation or any alternative way to simplify code in javascript
if(req.query.pr=="trans"){
util.transUrl(req.originalUrl).then(param => {
res.redirect(param);
})
}
else if(req.query.pr=="inst"){
util.instaUrl(req.originalUrl).then(param => {
res.redirect(param);
})
}
else{
res.status(400).send("Contact the editor of the originating page.")
}
There are multiple ways to write a conditional statement in JS. However, if there are multiple statements I would say you should stick to if else if else. But if you want to see other approaches, here they are:
Using Ternary operator ? :
const {pr} = req.query
pr === 'trans'
? util.transUrl(req.originalUrl).then(param =>
res.redirect(param)
)
: pr === 'inst'
? util.instaUrl(req.originalUrl).then(param =>
res.redirect(param)
)
: res.status(400).send('Contact the editor of the originating page.')
Using Gate logic && ||
const {pr} = req.query
(pr === 'trans' &&
util.transUrl(req.originalUrl).then(param =>
res.redirect(param))
) ||
(pr=== 'inst' &&
util.instaUrl(req.originalUrl).then(param =>
res.redirect(param))
) ||
res.status(400).send('Contact the editor of the originating page.')
Now, Looking at your code, here if and else if statements are similar. So you can avoid else if using ternary operator like this:
const {pr} = req.query
if(pr === 'trans' || pr === 'inst'){
util[pr === 'trans' ? 'transUrl' : 'instaUrl'](req.originalUrl)
.then(param => res.redirect(param))
}
else{
res.status(400).send('Contact the editor of the originating page.')
}
Just one FYI: Please consider using === instead of == whenever you are comparing strings and there is no need of coercion.
Related
const {
service,
customer,
company,
parking,
aircraftType,
aircraft,
endPlan,
startPlan,
heatingPointsMasterCodes,
lavatoryType,
passengersCategory } = formValues;
useEffect(() => {
customer &&
company &&
(parking || service === ReferenceCodesOfServicesEnum.ProvisioningMinibus) &&
aircraftType &&
aircraft &&
endPlan &&
startPlan &&
(heatingPointsMasterCodes ||
lavatoryType ||
passengersCategory ||
formValues[DocumentItemNamesEnum.WaterSystemMaintenance] ||
service === ReferenceCodesOfServicesEnum.AircraftCooling)
? setDisabled(false)
: setDisabled(true);
}, [formValues]);
So my question is, how to optimize or reduce variable check for true value?
First i get variables with destructing from object, then check same variables for true value.
I think i can somehow optimize this, but dont know how
In general if you have a series of if checks you could consider turning it into a switch instead. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Since you're mostly checking to make sure things are defined, but also have some more nuanced requirements, it may be better break it up slightly:
// Properties required irrespective of environment properties in DocumentItemNamesEnum or ReferenceCodesOfServicesEnum
const requiredProperties = ["customer",
"company", "aircraftType",
"aircraft", "endPlan",
"startPlan"]
const requiredPropertiesDefined = requiredProperties.every(value => !!value)
useEffect(() => {
if (requiredPropertiesDefined &&
(formValues.parking || formValues.service === ReferenceCodesOfServicesEnum.ProvisioningMinibus) &&
&& (formValues.heatingPointsMasterCodes ||
formValues.lavatoryType ||
formValues.passengersCategory ||
formValues[DocumentItemNamesEnum.WaterSystemMaintenance] ||
service === ReferenceCodesOfServicesEnum.AircraftCooling) {
setDisabled(true)
} else {
setDisabled(false
}
}, [formValues])
If you want to check if all values of object are truthy then following code can be used.
Object.values(formValues).every(value => !!value)
I am using node.js and trying to query based on multiple filters if only they are true
select * from orders ${isFilter ? 'where' : ''}
${orderId !== undefined && orderId ? `order_id = '${orderId}' or ` : '' }
${receiptId !== undefined && receiptId? `receipt_id = '${receiptId}' or `: '' }
${driver !== undefined && driver ? `driver_id = '${Number(driver)}'` : '' }
this works fine where there is no filter or when all the filters are true but the OR causes an issue when one filter or more are missing. what would be the best way to handle this ?
This is a pseudo code to dynamically compose the query
var clause = 'where';
var query = 'select * from orders';
if (isFilter) { // this statement could be removed
if (orderId !== undefined && orderId) {
query += clause + ' order_id = `${orderId}`';
clause = 'or';
}
if (receiptId !== undefined && receiptId) {
query += clause + ' receiptId = `${receiptId}`';
clause = 'or';
}
if (driver !== undefined && driver) {
query += clause + ' driver = `${driver}`';
clause = 'or'; // this is not really needed, but it could be useful for further filters in future
}
}
let whereClause = [];
if(orderId) whereClause.push(`order_id = '${orderId}'`);
if(receiptId) whereClause.push(`receipt_id = '${receiptId}'`);
if(driver) whereClause.push(`driver_id = ${parseInt(driver)}`);
let whereQuery = whereClause.join(' OR ');
let sql = `select * from orders where true ${whereClause.length ? whereQuery : ''}`;
try using join. so that you can add many properties even not in order. Also if you're expecting it to be undefined, then you may remove that as it resulted false on condition statement.
I think it would be reasonable if you can log the query. we can be sure about the query that's being sent.
This would be the first step to troubleshoot and may be we can use the way you are trying using ternary operator with few changes.
The code you used above to build the query string is not possible to cover all possible cases.
Example:
What if isFilter==false and one of the 3 variables orderId, receiptId and driver has the value !== undefined? => your query will be wrong because the WHERE statement is missing.
Another case, if one of the variables orderId or receiptId satisfied the condition and the variable driver is not valid. => Your query will be wrong because of the extra of 'OR' at the end.
Those are the 2 cases that are most likely to cause problems for the above code. Here is my suggestion to solve your problem:
queryString="select * from orders"
if(isFilter){
queryString+=' where'
if(orderId){
queryString+=' ..... or'
}
if(receiptId){
queryString+=' ..... or'
}
if(driver){
queryString+=' .....'
}
}
queryString=queryString.trim()
if(queryString.endsWith('or')){
queryString=queryString.substring(0,queryString.length-2)
}
if(queryString.endsWith('where')){
queryString=queryString.substring(0,queryString.length-5)
}
select * from orders ${isFilter ? 'where 1=0' : ''}
${orderId !== undefined && orderId ? `OR order_id = '${orderId}' ` : '' }
${receiptId !== undefined && receiptId? `OR receipt_id = '${receiptId}' `: '' }
${driver !== undefined && driver ? `OR driver_id = '${Number(driver)}'` : '' }
Instead if its AND you can do 1=1 instead of 1=0.
i have caluclateAcess function which takes an array as input ,
the array will have max of three elements and min of one element
so the possible elements it can come is create, read and update
so its basically 2^3 which means 8 probabablities can come so
i am listing down all the probabablities and returning a value
i will list down the possible input and what output should i return. Array of empty wont be comming which means false, false, false
create => 'CreateAndRead'
read => 'Read'
update => 'UpdateAndRead'
create,read => 'CreateAndRead'
update, read => 'UpdateAndRead'
create, update => 'ALL'
create,read, update => 'ALL'
so i have written the below function is there any better way to achieve this
let READ = 'read';
let CREATE = 'create';
let UPDATE = 'update';
const caluclateAcess = (inputArray) => {
if (
(inputArray.indexOf(READ) > -1
&& inputArray.indexOf(UPDATE) > -1
&& inputArray.indexOf(CREATE) > -1)
||
(
inputArray.indexOf(UPDATE) > -1
&& inputArray.indexOf(CREATE) > -1
)
) {
return 'ALL';
}
if (
(inputArray.indexOf(CREATE) > -1
&& inputArray.indexOf(READ) > -1)
|| (inputArray.indexOf(CREATE) > -1
&& (inputArray.indexOf(READ) === -1 && inputArray.indexOf(UPDATE) === -1))
) {
return 'CreateAndRead';
}
if (
(inputArray.indexOf(UPDATE) > -1
&& inputArray.indexOf(READ) > -1)
|| (inputArray.indexOf(UPDATE) > -1
&& (inputArray.indexOf(READ) === -1 && inputArray.indexOf(CREATE) === -1))
) {
return 'UpdateAndRead';
}
if (inputArray.indexOf(READ) > -1) {
return 'Read';
}
};
Any help appreciated
You can start off by removing the repeat inputArray.indexOf() calls - it makes everything harder to read. It's simpler to check these once only:
const hasCreate = inputArray.indexOf(CREATE) > -1;
const hasUpdate = inputArray.indexOf(UPDATE) > -1;
const hasRead = inputArray.indexOf(READ) > -1;
Second, the rules you set up show that you have three access properties - read, update, and create, each one may imply another. Looking at those, it becomes clear that you have the following relationships:
read => read
update => update, read
create => create, read
Thus, update and create are actually compound. This means that the initial check can be modified to account for these:
const hasCreate = inputArray.indexOf(CREATE) > -1;
const hasUpdate = inputArray.indexOf(UPDATE) > -1;
const hasRead = hasCreate || hasUpdate || inputArray.indexOf(READ) > -1;
This avoids having the checks for if somebody has read or update.
As an extra note, you can just use Array#includes instead of checking the index.
With that said, the read right is pretty much inconsequential. It matters if it's the only one available, in all other cases it's pretty much ignored or assumed to be present. Still, it's useful to model the implied rules - perhaps this can change in the future.
Finally, the logic is too complex. There are only four possible final states and as mentioned above, read is not even used for most of them. Here is the updated code that does all the checks. I've added another state called "None" for the case when there are no permissions at all. Even if it's not possible for this to happen, I find it easier to just have it and it be unused than omit it:
const caluclateAcess = (inputArray) => {
const hasCreate = inputArray.includes('create');
const hasUpdate = inputArray.includes('update');
const hasRead = hasCreate || hasUpdate || inputArray.includes('read');
if (hasCreate === true && hasUpdate === true) return "ALL";
if (hasCreate) return "CreateAndRead";
if (hasUpdate) return "UpdateAndRead";
if (hasRead) return "Read";
return "None";
};
console.log("create =>", caluclateAcess(["create"]) );
console.log("read =>", caluclateAcess(["read"]) );
console.log("update =>", caluclateAcess(["update"]) );
console.log("create, read =>", caluclateAcess(["create", "read"]) );
console.log("update, read=>", caluclateAcess(["update", "read"]) );
console.log("create, update =>", caluclateAcess(["create", "update"]) );
console.log("create, read, update =>", caluclateAcess(["create", "read", "update"]));
console.log("<nothing> =>", caluclateAcess([]) );
The READ, CREATE, and UPDATE variables are not needed, since they are only used once, so I inlined them to shorten the code even more.
However, if there really is no possibility for an empty array of access properties, then that implies that the read access is completely inconsequential. It's impossible to not have it. So, checking for it can be entirely skipped and the default return value of the function can be changed from "None" to "Read". However, my personal preference is to keep the check - it doesn't hurt any of the functionality and the implementation produces no deviation from the specs. If the specs change in the future, or there is some sort of bug, it's probably better to not automatically grant read access.
I have this condition which verifies the same property labelKey of an object projectType and return of different value according to the value of the property
checkProjectType () {
if (this.projectType.labelKey === 'project_type.rent') {
return 'geographical_area'
} else if (this.projectType.labelKey === 'project_type.buying') {
return 'geographical_area'
} else {
return 'address'
}
}
since there is too much resemblance in the condition how I refactored / optimized the condition with a simplified write using Lodash or ECMAScript 2015 for example ?
You can reduce this to less conditions as per your code.
checkProjectType () {
var labelKey = this.projectType.labelKey;
if (labelKey === 'project_type.rent' || labelKey === 'project_type.buying') {
return 'geographical_area';
}
return 'address';
}
Not sure what you want to do here with lodash
I also don't like if-else-if… chains, so prefer more readable variant.
function checkProjectType() {
const defaultType = 'address';
const key = this.projectType.labelKey;
let map = {
'project_type.rent': 'geographical_area',
'project_type.buying': 'geographical_area'
};
return map[key] || defaultType;
}
map can be defined somewhere else.
Setting an if do X else if do X else do Y is wrong to me, you can simplify that in a single line : if (this.projectType.labelKey === 'project_type.rent' || this.projectType.labelKey === 'project_type.buying') would be easier to read already.
One alternative way this could be written is using a switch statement:
switch (this.projectType.labelKey) {
case 'project_type.rent':
case 'project_type.buying':
return 'geographical_area';
default:
return 'address';
}
But one might argue it's a bit overkill in this case. Lodash or ECMAScript 2015 isn't going to do anything for you here.
You can check if the project type is included in an array of types, and use a ternary to select the response:
checkProjectType() {
return ['project_type.rent', 'project_type.buying'].includes(this.projectType) ? 'geographical_area' : 'address';
}
If the types that produce geographical_area, you can refactored them out of the method (and the object/class):
const geoTypes = ['project_type.rent', 'project_type.buying'];
checkProjectType() {
return geoTypes.includes(this.projectType) ? 'geographical_area' : 'address';
}
i work for a bbs app recently, and when i use the aql, i got a problem, for example:
//params:.com/t/123?&digest=true
=>
FOR t IN threads
FILTER t.digest == true && some conditions
RETURN t
and the result is as expected,but when the parameter 'digest' is undefined or false, i want it returns all the threads..not which 'digest' = false, so i have to use if...else to write two almost same code, just remove the condition 't.digest == true' for example:
if(params.digest) {
return `digest == true && conditions`
}
return `conditions`
i'm using javascript, please give me a direction...
You can use the function HAS(document, attributeName) to check whether the attribute is present in the document.
FOR t IN threads
FILTER (!HAS(t,"digest") || i.digest == true) && conditions
RETURN t