wailer
wailer

Reputation: 551

how to manage 100's of else if statement in javascript? better way?

I am learning javascript. I am trying to answer my quiz - classify urls. How can I improve my answer for classifying 100 urls.. my answer is not so efficient.. any help? thanks.

var pageURL = document.location.href;
var isHealth = pageURL.indexOf("http://www.domain.com/health/");
var isCar = pageURL.indexOf("http://www.domain.com/car/");
var isFuel = pageURL.indexOf("http://www.domain.com/fuel/");
var isRoadside = pageURL.indexOf("http://www.domain.com/roadside/");

if (isHealth > -1) {
return 'health';
} else if (isCar > -1) {
return 'car';
} else if (isRoadside > -1) {
return 'roadside';
} else if (isFuel > -1) {
return 'fuel';
} else return 'other';

Upvotes: 2

Views: 270

Answers (4)

giannisf
giannisf

Reputation: 2599

why not ?

    var pages = ['health', 'car', 'fuel'] 
    var page = pageURL.split('//')[1].split('/')[1] || -1;
    var index = pages.indexOf(page)

if (index !=-1) 
    return pages[index]
else
  return 'other'

Upvotes: 1

dfsq
dfsq

Reputation: 193311

You can use map object and for loop to check what url matches current page:

var urls = {
    health: "http://www.domain.com/health/",
    car: "http://www.domain.com/car/",
    roadside: "http://www.domain.com/fuel/",
    fuel: "http://www.domain.com/roadside/"
};

var pageURL = document.location.href;

for (var key in urls) {
    if (pageUrl.indexOf(urls[key]) > -1) {
        return key;
    }
}
return "other";

Upvotes: 6

Shomz
Shomz

Reputation: 37701

You can map them together like this, but I'm not sure if it's worth it:

var map = {
    'health': isHealth,
    'car': isCar,
    'roadside': isRoadside,
    'fuel': isFuel
}

for (var i in map) {
    if (map[i] > -1) {
        return i;
    }
}
return 'other';

That's the general approach.


Better idea

But, your specific problem is easily solvable using regex:

var match = pageURL.match(/http:\/\/www.domain.com\/(.+)\//);
return (match && match[1]) || 'other';

See this live example:

function test(pageURL) {
  var match = pageURL.match(/http:\/\/www.domain.com\/(.+)\//);
  return (match && match[1]) || 'other';
}

alert(test('http://www.domain.com/health/'));   // health
alert(test('http://www.domain.com/whatever/')); // whatever
alert(test('http://www.domain.com/'));          // other

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120546

"JavaScript Trie Performance Analysis" discusses how to use Tries in JavaScript to do compact, efficient prefix lookup.

It looks like most of your checks can be boiled down to "does the string s start with a URL prefix." This kind of longest prefix check is exactly what Tries were designed to do.

If the bodies of your if ... else if ... else are not formulaic, you could store functions encapsulating those bodies as the value of the trie.

Upvotes: 0

Related Questions