"OR"operator won;t work in this switch-case - javascript

In below try block we have a switch-case but when the channeling is phone_pe it goes into the phonePeScheduler func. but whenever i pass channeling as phonepe it is going into the default block. How can we modify the first case I want both the string.
try {
const channeling =
body?.data?.channel ||
body?.data_link?.channel;
switch (channeling) {
case "phone_pe" || "phonepe":
await phonePeScheduler(body, reqId);
break;
case "Gpay":
await gpayScheduler(body);
break;
case "cash":
default:
await paymentHandling(body);
}
I tried doing multiple things but they didnt worked.

That's not the correct syntax. You cannot use || operator directly in case but you can use multiple case values without using a break between them, so your code becomes:
try {
const channeling =
body?.data?.channel ||
body?.data_link?.channel;
switch (channeling) {
case "phone_pe":
case "phonepe":
await phonePeScheduler(body, reqId);
break;
case "Gpay":
await gpayScheduler(body);
break;
case "cash":
default:
await paymentHandling(body);
}

Related

How to solve this switch-case problem, when my clause is not working for one case [duplicate]

This question already has answers here:
How to avoid 'cannot read property of undefined' errors?
(18 answers)
Closed 26 days ago.
The community is reviewing whether to reopen this question as of 26 days ago.
Here in the below switch-case condition it is throwing error
Cannot read property 'entity' of undefined because for every other case except "paytm" the entity is present in the "payload" but for paytm its "payload_data" --> body.data.payload_data.entity.channel
How to solve this issue.
switch(body.data.payload.entity.channel){
case "paytm" :
await paytm(body);
break;
case "phonePe" :
await phonePe(body);
break;
case "googlePay":
default:
await googlePay(body);
}
I tried adding multiple things but it didnt worked for me.
Use optional chain operator
const targetChannel =
body?.data?.payload?.entity?.channel ||
body.data.payload_data.entity.channel;
switch (targetChannel) {
case "paytm":
await paytm(body);
break;
case "phonePe":
await phonePe(body);
break;
case "googlePay":
default:
await googlePay(body);
}
You can use the nullish coalescing operator (??) to ensure that if the payload property is not present, then the payload_data property is used instead:
You can repeatedly press the "Run code snippet" button below to see randomized results in the console.
<script type="module">
function simulateRandomBody () {
const channel = Math.random() < 0.5 ? "phonePe" : "googlePay";
return Math.random() < 0.5
? { data: { payload: { entity: { channel } } } }
: { data: { payload_data: { entity: { channel: "paytm" } } } };
}
const paytm = console.log.bind(console);
const phonePe = console.log.bind(console);
const googlePay = console.log.bind(console);
const body = simulateRandomBody();
switch ((body.data.payload ?? body.data.payload_data).entity.channel) {
case "paytm":
await paytm(body);
break;
case "phonePe":
await phonePe(body);
break;
case "googlePay":
default:
await googlePay(body);
}
</script>

The fetch fonction load infinitely (Shopify)

I have try this but I wasn't able to add a cookie or locale storage condition so it won't reload infinitely.
fetch('https://get.geojs.io/v1/ip/country')
.then(response => response.text())
.then(country_code => {
var domain_and_tld = window.location.host.split('.').splice(-2).join('.');
country_code = country_code.trim().toLowerCase();
switch (country_code) {
case 'us':
window.location.host = domain_and_tld;
break;
case 'gb':
window.location.host = `${domain_and_tld}?currency=GBP`;
break;
case 'fr':
window.location.host = `${domain_and_tld}?currency=EUR`;
break;
};
})
.catch(err => console.error(err));
Thanks for your help :)
It seems you want to change the query params based on the users country. We don't need to change window.location.host. You can change query params using window.location.search.
However, you only want to change window.location.search if it does not match your desired value (to avoid reloading infinitely). The solution below assumes currency is the only query param in your URL.
fetch('https://get.geojs.io/v1/ip/country')
.then(response => response.text())
.then(country_code => {
const country_code = country_code.trim().toLowerCase();
let desiredSearchParams = '';
switch (country_code) {
case 'gb':
desiredSearchParams = `?currency=GBP`;
break;
case 'fr':
desiredSearchParams = `?currency=EUR`;
break;
case 'us':
default:
break;
};
if(desiredSearchParams !== window.location.search) {
//change search param only if desired search param different from current search param
window.location.search = desiredSearchParams;
}
})
.catch(err => console.error(err));

Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed

On Sonarqube I'm getting this as critical issue, can somebody help me in this to sort out this issue.
Here is the code details, please let me know how can I refactor this code with switch case :
const getEmailTo = (subject) => {
switch (subject) {
case 'POWERUP_REWARDS':
return COMMON_EMAIL;
case 'GAME_INFORMER':
return COMMON_EMAIL;
case 'ONLINE_ORDER':
return 'test#gmail.com';
case 'STORE_EXPERIENCE':
return 'test#gmail.com';
case 'APP_REVIEW':
return COMMON_EMAIL;
case 'SOMETHING_ELSE':
return COMMON_EMAIL;
default:
return '';
}
};
Make your code a bit more DRY and simplified by collecting your common cases that return the same values. I don't think SonarQube validates readability, but proper use of whitespace can go a long way in readability of unfamiliar code. It's opinionated, but I like a line between case returns.
const getEmailTo = (subject) => {
switch (subject) {
case 'POWERUP_REWARDS':
case 'GAME_INFORMER':
case 'APP_REVIEW':
case 'SOMETHING_ELSE':
return COMMON_EMAIL;
case 'ONLINE_ORDER':
case 'STORE_EXPERIENCE':
return 'test#gmail.com';
default:
return '';
}
};
You can use an object to map subjects to email addresses and return the email address corresponding to the subject.
const TEST_EMAIL = 'test#gmail.com'
const emails = {
POWERUP_REWARDS: COMMON_EMAIL,
GAME_INFORMER: COMMON_EMAIL,
APP_REVIEW: COMMON_EMAIL,
SOMETHING_ELSE: COMMON_EMAIL,
ONLINE_ORDER: TEST_EMAIL,
STORE_EXPERIENCE: TEST_EMAIL,
}
const getEmailTo = (subject) => emails[subject] || ''
I'm not sure if returning '' is fine when a subject is not in the mapping. I would suggest throwing an error to let the caller know the subject is invalid.
const getEmailTo = (subject) => {
if (!(subject in emails)) {
throw new Error(`Invalid subject: ${subject}`)
}
return emails[subject]
}
You can just put the related case statements next to each other, like this:
const getEmailTo = (subject) => {
switch (subject) {
case 'POWERUP_REWARDS':
case 'GAME_INFORMER':
case 'APP_REVIEW':
case 'SOMETHING_ELSE':
return COMMON_EMAIL;
case 'ONLINE_ORDER':
case 'STORE_EXPERIENCE':
return 'test#gmail.com';
default:
return '';
}
};

What's the easiest way to use a switch statement when I don't know how many things need to be compared against?

So I have a terminal into which the user types commands.
I take the first phrase of the command and run it through a switch statement to work out what to do.
switch(phrases[0]) {
case "boot":
// Do something
break;
case "switch":
case "app":
case "change":
case "switchapp":
case "changeapp":
// Do something
break;
case "help":
// Do something
break;
case "wipe":
case "erase":
case "restart":
case "forget":
case "clear":
case "undo":
// Do something else here
break;
default:
throw new Error("Unknown command: " + phrases[0]);
}
Note that for each command I've got a few alternatives to make it more likely for the user to pick a correct command on their first try.
However - if I have all of those alternatives in an array instead of hard-coded into the switch function, how do I access them?
I've considered using if/else combined with .some() but that seems clunky:
if(bootCommands.some(function(name){return name == phrases[0]}))
// Do something
if(switchCommands.some(function(name){return name == phrases[0]})) {
// Do something
} else if(helpCommands.some(function(name){return name == phrases[0]})) {
// Do something
} else if(wipeCommands.some(function(name){return name == phrases[0]})) {
// Do something
} else {
throw new Error("Unknown command: " + phrases[0]);
}
There's an easier way, surely?
You can still use switch-case expression with Array.includes()
switch(true) {
case bootCommands.includes(phrases[0]):
// Do something
break;
case wipeCommands.includes(phrases[0]):
// Do something
break;
default:
throw new Error("Unknown command: " + phrases[0]);
}
var bootCommands = ["boot"],
wipeCommands = ["wipe", "erase", "restart", "forget", "clear", "undo"],
command = "restart";
switch (true) {
case bootCommands.includes(command):
// Do something
console.log("Boot command: " + command);
break;
case wipeCommands.includes(command):
// Do something
console.log("Wipe command: " + command);
break;
default:
console.log("Unknown command: " + command);
}

node_redis client - Cannot return out values from a query

I'm going crazy with a problem which I can not find solution. I can not return out values from a redis query. I am using node_redis client (http://redis.js.org/) as redis driver for Node.JS.
The problem is: I wrote a function for get the user status connection and return it for take the value from other function.
//CHECK USER STATUS
exports.checkUserStatus = function(uid){
redis.multi()
.sismember('users:online',uid)
.sismember('users:iddle', uid)
.sismember('users:out', uid)
.sismember('users:locked', uid)
.exec(function(err, res){
res.forEach(function(res, index){
if(res != 0){
switch(index){
case 0:
return 'online';
break;
case 1:
return 'iddle';
break;
case 2:
return 'out';
break;
case 3:
return 'locked';
break;
default:
return 'offline';
}
}
});
})
}
But function return nothing!. If I replace the return line with a console.log(), it work! but I don't need a console.log(), I need take the value.
I tried too create a variable outside of the query and set it from inside and then return it but, it doesn't work.
Somebody know how may I do that?
Thank you!
I'm not a redis expert but ... maybe you simply missing the return keyword?
var result;
exports.checkUserStatus = function(uid){
redis.multi()
...
.exec(function(err, res){
res.forEach(function(res, index){
if(res != 0){
switch(index){
case 0:
result = 'online';
break;
case 1:
result ='iddle';
break;
case 2:
result = 'out';
break;
case 3:
result = 'locked';
break;
default:
result = 'offline';
}
}
});
})
return result;
}
Based on manual from http://redis.io/commands/MULTI multi returns value, which you doesn't return.
In this site but, in spanish I received the right answer. I post here for help to others:
//CHECK USER STATUS ... Take a look at the new parameter 'callback' in the function!
exports.checkUserStatus = function(uid, callback){
redis.multi()
.sismember('users:online',uid)
.sismember('users:iddle', uid)
.sismember('users:out', uid)
.sismember('users:locked', uid)
.exec(function(err, res){
res.forEach(function(res, index){
if(res != 0){
switch(index){
case 0:
// Here invoke the user's function
// and I pass the info
callback('online');
break;
case 1:
callback('online');
break;
case 2:
callback('online');
break;
case 3:
callback('locked');
break;
default:
callback('offline');
}
}
});
})
}
And then I catch the returned value as you will see below:
// sequence of events
// This happend first - #1
checkUserStatus('uid-12343', function(status, user) {
// This happend at the end - #2
// Here we catch the status in asynchronous way
});
// This happend second - #2
console.log("This happend before the redis info arrive!");
Thank you to everyone! I hope I've helped!

Categories