J.S.C
J.S.C

Reputation: 1543

Increase performance of else-if chain

I'm building my service on NodeJs. I have a web-scraping function and I have to call different crawlers for different domains.

if (domain == "aaa.kr") result = await crawlAA(args.url)
else if (domain == "aaa.com") result = await crawlA(args.url)
else if (domain == "bbb.com") result = await crawlB(args.url)
else if (domain == "ccc.com") result = await crawlC(args.url)
else if (domain == "d.com") result = await crawlD(args.url)
else result = await crawlOthers(args.url)

Right now, I have about 10 else if clauses. However, I will need to add more than 50~100 else-ifs and I am thinking this can be a problem in the future.

Are there any efficient way to handle string if-clauses? Will primarily filtering by the starting alphabet help?

Upvotes: 0

Views: 42

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Performance is almost certainly not an issue here - there are no loops or nested loops, The issue here is the very WET code, if you have lots of else/ifs.

Instead of having lots of standalone crawl functions, use an object indexed by the domain instead, eg:

const fns = {
  'aaa.kr': <code of crawlAA here>,
  'aaa.com': <code of crawlA here>,
  'bbb.com': <code of crawlB here>,
  // ...
};

Then find the appropriate function-value on the object when trying to find a result, and call it:

const fn = fns[domain];
const result = fn ? fn(args.url) : crawlOthers(args.url);

Upvotes: 2

Related Questions