Im trying to find way to make the code work the same way shown in the code below using the other methods to if/else statements. Can anyone help me with that? I have a lot more cities and clearly this isn't going to scale.
function getCityNameFromURL() {
var curURL = "" + Request.ServerVariables("URL");
var returnCityName = "";
curURL = curURL.toLowerCase();
if (curURL.indexOf("/sgncp/") != -1 || curURL.indexOf("/mlgct/") != -1)
returnCityName = "London";
if (
curURL.indexOf("/berlinplus/") != -1 ||
curURL.indexOf("/berlinadmin/") != -1
)
returnCityName = "Berlin";
else if (
curURL.indexOf("/tokyoplus/") != -1 ||
curURL.indexOf("/tokyoadmin/") != -1
)
returnCityName = "Tokyo";
else if (
curURL.indexOf("/parisplus/") != -1 ||
curURL.indexOf("/parisadmin/") != -1
)
returnCityName = "Paris";
return returnCityName;
}
How about a more simple configuration based code? You could even move the city mapping info in to a separate resource.
This would allow simpler updates without having to write extra code.
function getCityNameFromURL() {
var curURL = "" + Request.ServerVariables("URL");
curURL = curURL.toLowerCase();
var cityMappings = [
{ code: '/sgncp/', city: 'London' },
{ code: '/mlgct/', city: 'London' },
{ code: '/berlinplus/', city: 'Berlin' },
{ code: '/berlinadmin/', city: 'Berlin' },
{ code: '/tokyoplus/', city: 'Tokyo' },
{ code: '/tokyoadmin/', city: 'Tokyo' },
{ code: '/parisplus/', city: 'Paris' },
{ code: '/parisadmin/', city: 'Paris' }
];
return cityMappings
.find(mapping => curURL.indexOf(mapping.code) >= 0)
?.city ?? '';
}
Note also, the null-conditional ?. when attempting to access the city property just incase the URL doesn't match any of them and returns an empty string.
Version with for loop
Replace the cityMappings.find code with this
for (let i = 0; i < cityMappings.length; i++){
const mapping = cityMappings[i];
if (curURL.indexOf(mapping.code) >= 0)
return mapping.city;
}
// in case no match was found return an emtpy string.
return '';
This answer is very similar to the one already given by phuzi.
This answer also introduces a city mapping, but in a somewhat different manner to reduce string duplication. I've also introduced a defaultCity variable to (arguably) improve code readability.
function getCityNameFromURL() {
const curURL = ("" + Request.ServerVariables("URL")).toLowerCase();
const defaultCity = { name: "" };
const cities = [
{ name: "London", patterns: ["/sgncp/", "/mlgct/" ] },
{ name: "Berlin", patterns: ["/berlinplus/", "/berlinadmin/"] },
{ name: "Tokyo", patterns: ["/tokyoplus/", "/tokyoadmin/" ] },
{ name: "Paris", patterns: ["/parisplus/", "/parisadmin/" ] },
];
const city = cities.find(({ patterns }) => (
patterns.some(pattern => curURL.includes(pattern))
)) || defaultCity;
return city.name;
}
Or if you prefer a for-loop:
for (const { name, patterns } of cities) {
for (const pattern of patterns) {
if (curURL.includes(pattern)) return name;
}
}
return "";