Regex in a switch statement

While working for a client I recently came across an interesting problem. The routing architecture was designed in a particular way which prevented users from directly accessing a page by using a specific URL to the resource. Users had to click their way through the app to get to a specific user or location.

A square peg and a round hole

This proved to be a challenge when a new requirement came up to allow administrators to send links to managers for individual locations.

The links were in the form of http://foo.bar/location/[locationId]/manage

We were able to generate these links directly but the infrastructure to navigate to them didn’t exist and since the entire code base is going to be rewritten with only the necessary modules first, there wasn’t really an incentive to redo the entire routing architecture.

Trying to square the round hole

The approach taken was to create an http interceptor for the app and only trigger the direct navigation mechanism for very specific URLs.

The first draft of the app had a bunch of if statements which would perform Regex evaluations for each of the specified URLs and return a result only on matches. It worked well enough to fix the problem but we didn’t really liked the way it looked. It looked a little clumsy so we tried cleaning it up a bit and ended with a nicer solution.

The solution

Instead of using if statements we wrapped everything up in a switch statement.

getRedirectPage(part: string) {
   switch (true){
       case /location\/\d+\/manage/.test(part): 
           return 'LocationManagePage';
       case /user\/\d+\/profile/.test(part): 
           return 'UserProfilePage';
       default:
           return '';            
   }
}

The return value of the .test() function is of type boolean and only one of the expressions will (or should) return true and match the control value passed to the switch statement which in turn executes a specific block of code which returns the correct page to navigate to.

More often than not, this will be just syntactic sugar, even though switch statements can be more optimized than if statements (link), in our case the performance will pretty much be identical.

Next time we will look into one big performance issue in Angular and Ionic applications - having function calls inside the HTML template and discuss some solutions to this problem.

Until then,
Happy coding