Home > Enterprise >  Javascript - smartest solution for many conditions
Javascript - smartest solution for many conditions

Time:10-24

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.:

    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.

CodePudding user response:

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";
)

CodePudding user response:

load the settings from a json file, like this:

const jsonText = `{
  "pages": {
    "something": "main/contact",
    "anythingelse": "administration/user"
  }
}`;
let pages = JSON.parse(jsonText).pages;

console.log('pages["something"]:', pages['something']);
console.log('pages["anythingelse"]:', pages['anythingelse']);
console.log('pages["not_found"]:', pages['not_found']);

  • Related