Angular: Comparing the Performance of Switch Statements and Dictionary Lookups

Having trouble deciding between two options for parsing URL parameters? Both seem suboptimal, but is there a better way to handle this situation? If you have any suggestions for a plausible Option #3, please share. Let's assume we are dealing with up to 40 parameters.

Option #1

Cons: The complexity is O(n*k), where n is the number of parameters and k is the number of switch cases. Also, the overall logic looks quite messy.

for(let param in params) {
  let value = params[param];
  switch(param){
    case 'param1': {
      doSomethingWithParam1(value);
      break;
    }
    case 'param2': {
      doSomethingWithParam2(value);
      break;
    }
  }
}

Option #2

Pros: The complexity is reduced to O(k).

Cons: However, the code structure appears even more convoluted.

let param = '';
param = 'param1';
if(param in params){
  let value = params[param];
  doSomethingWithParam1(value);
}
param = 'param2';
if(param in params){
  let value = params[param];
  doSomethingWithParam2(value);
}

Answer №1

One interesting feature of TypeScript is that it is a superset of JavaScript, allowing you to create objects with functions and call them by key:

let functions = {
    f1: function(){
        console.log(`it is f1 function`)
    },
    f2: function(){
        console.log(`it is f2 function`)
    },
    f3: function(){
        console.log(`it is f3 function`)
    }
}

let param = '';
param = 'f1';

console.log(functions[param]());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating with nginx

My Angular2 application works perfectly fine when using the local webpack dev server. However, after deploying the application on a server behind nginx, I am facing an issue. I can navigate using application links, but if I enter a URL directly into the br ...

Does having an excessive amount of variable declarations result in a noticeable decline in performance?

One thing I notice for the sake of readability is that I tend to create new variables for data that I already have on hand. I'm curious, does this impact performance significantly? Here's an example of what I mean: const isAdult = this.data.per ...

Resizing a d3 graph for various screen resolutions

Looking to create a dynamic dashboard in Angular, I found a code snippet for a gauge chart at this link. Here is an example of how my HTML file appears: <div fxLayout="row" fxLayoutAlign="space-around center" > <div fxFlex='33%'> ...

Tips for embedding different pages within a single page using Angular 5

My project consists of 4 pages. [ { path: 'page1', component: Page1Component }, { path: 'page2', component: Page2Component }, { path: 'page3', component: Page3Component }, { path: 'page4', component: Page4Co ...

Enhance the functionality of Immutable.js field by integrating a custom interface in Typescript

Imagine a scenario where the property name is field, essentially an immutable object. This means that methods like field.get('') and other immutable operations are available for use. Nevertheless, I have my own interface for this field which may ...

Setting up admin credentials with TypeScript in Firebase cloud functions

While working with Firebase cloud functions in JavaScript, I utilized the following code snippet to initialize admin: admin.initializeApp({ credential: admin.credential.cert(require('./key/firebase-adminsdk.json')), databaseURL: "https://app ...

My Angular2+ application is encountering errors with all components and modules displaying the message "Provider for Router not found."

After adding routing to my basic app through app.routing.ts, I encountered errors in all of my test files stating that no Router is provided. To resolve the errors, I found that I can add imports: [RouterTestingModule], but is there a way to globally impo ...

Enhancing Angular Material: requiring more user engagement for rendering to occur

Encountering an unusual issue with Angular Material: certain components require an additional event, like a click or mouse movement on the targeted div, to trigger the actual rendering process. For instance, when loading new rows in mat-table, some empty ...

When a const variable is declared within the composition-api setup(), it remains unchanged unless redeclared within the function scope

Being primarily a back-end developer, the front-end side of things is still relatively new to me. I'm aware that there are concepts in this domain that I haven't fully grasped yet, and despite my efforts, I'm unable to resolve a particular i ...

Start Angular application using SSL encryption

I am striving to launch my Angular (7+) project with an SSL certificate on localhost (https://localhost:4200). Following the guidance provided in this source - Get angular-cli to ng serve over HTTPS, I attempted the following steps: 1) angular.json { " ...

Configuring TypeScript for Firefox to recognize specific types such as browser.storage

As per the documentation from Mozilla, I should be able to utilize browser.storage.sync.get in my extension. However, I am encountering some challenges in getting TypeScript to recognize that I can use browser. I have attempted the following (which has wo ...

React: Using useState and useEffect to dynamically gather a real-time collection of 10 items

When I type a keystroke, I want to retrieve 10 usernames. Currently, I only get a username back if it exactly matches a username in the jsonplaceholder list. For example, if I type "Karia", nothing shows up until I type "Karianne". What I'm looking f ...

The Extended Date type is indicating that the function cannot be located

I came across this helpful gist with date extensions: https://gist.github.com/weslleih/b6e7628416a052963349494747aed659 However, when attempting to use the functions, I encountered a runtime error stating: TypeError: x.isToday is not a function I foun ...

Is it possible for NodeJS to redirect to an Angular5 route and return JSON instead of a webpage?

When using the API, I'm attempting to redirect a user if it is detected that they are no longer logged in. For example, if a user initiates an action (PUT) to the api, the API verifies the user's status. If the user is logged in, the action is ca ...

What is the best way to merge imported types from a relative path?

In my TypeScript project, I am utilizing custom typings by importing them into my .ts modules with the following import statement: import { MyCoolInterface } from './types' However, when I compile my project using tsc, I encounter an issue wher ...

Issue with Dropdown menu in Navbar on Bootstrap 5 when using ng add installation technique

Here's my current setup: I'm currently using Angular 11.2.11 and Bootstrap 5 on a Windows system. The project I'm working on utilizes SCSS. The Issue at Hand: I've been following the codes provided in the bootstrap documentation (whi ...

Displaying code within an Angular 2 template

Working on an Angular 2 project and facing a challenge in displaying C# code within the template, which may later be styled with syntax highlighter. The issue arises when attempting to insert the C# code into the Angular 2 template, resulting in template ...

Substitute data types for certain keys within a Typescript interface

Within this code snippet, the goal is to create a new type from an existing one by iterating through the keys and only replacing those that meet a specific condition. Additionally, union types are being utilized here. class A {} class B { constructor ...

Is there a way to use a single url in Angular for all routing purposes

My app's main page is accessed through this url: http://localhost:4200/ Every time the user clicks on a next button, a new screen is loaded with a different url pattern, examples of which are shown below: http://localhost:4200/screen/static/text/1/0 ...

npm - Configuring the maximum memory usage in npm

I encountered an error message while trying to build my Angular project, The error states: "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" I read somewhere that adjusting the max-old-space-size in npm could resolve this issue. How ...