Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – smartest solution for many conditions

In javascript I have a function, where I have too many conditions. I wonder what will be the smartest solution to rework this function.

Currently I have it like this. Of course there are more than 20 conditions, just for example I have 3 here:

function checkURL(pageName) (
let urlPart = '';
if (pageName == 'something') { urlPart = "main/contact";}
if (pageName == 'anythingelse') { urlPart = "administration/user";}
if (pageName == 'another page') { urlPart = "administration/country";}

return urlPart;
)

I was thinking to rework it with switch/case or put the pageName variable into array and urlPart as well, and then just find the pageName position in array and compare with urlPart position, e.g.:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    function checkURL(pageName) (
const pg = ["something", "anythingelse", "another page"];
const url = ["main/contact", "administration/user", "administration/country"];

let index1 = pg.indexOf(pageName);
if (index1>=0) {return url[index1];} else {return ''; }
)

The problem might be with matching the same position of both elements in array, as people will add more and more items to the array and they can do a mistake where the position in first array will not match the correct position in second array when we will have 50 items maybe.

>Solution :

You don’t need to use checks at all for this.

Simply create an object that is used as a kind of lookup table. So in the case of your code, something like this:

const urls = {
  "something": "main/contact",
  "anythingelse": "administration/user",
  "another page": "administration/country"
}

Now you don’t need to run a bunch of checks, but a single check (that the urls object has a key that matches pageName). If that check succeeds, return the result. Otherwise, return a default / error page.

function checkURL(pageName) (
  return urls[pageName] || "main/pageNotFound";
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading