What is the most efficient way to minimize the use of if statements in an Angular component when calling a specific function?

Currently, I am working on an Angular 7 temperature conversion application. Within my formGroup, there are inputs and outputs along with two multi-select dropdowns where users can choose the unit of temperature 'From' and 'To' for conversion (Celsius, Fahrenheit, or Kelvin).

Upon submitting the form in my component, I retrieve the input data using the following function:

submitForm(data) {
    this.input = data.input;
    this.unitInput= data.unitInput;
    this.unitTarget= data.unitTarget;
    this.output= data.output;
}

Initially, I was planning to use multiple `if` statements to determine which conversion function to call based on the selected units. However, having a long list of `if` statements seemed inefficient and poorly designed.

if (this.inputUnit === 'Celsius' && this.targetUnit === 'Fahrenheit') {
    this.celsiusToFahrenheitConversion();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Kelvin') {
    this.celsiusToKelvinConversion();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Rankine') {
    this.celsiusToRankineConversion();
}

This approach led to branching `if` blocks for different unit conversions like Fahrenheit, Kelvin, Rankine, and more. What if new types of units need to be added in the future? This made me reconsider my strategy.

If you have any suggestions or better approaches, I would appreciate your insights. Thank you!

Answer №1

In my opinion, the most efficient solution for this problem would involve using a switch statement. While I understand that switch statements may not be everyone's favorite, sometimes they are necessary to handle certain scenarios.

switch(this.inputType) {
  case 'Celsius':
    switch(this.targetUnit) {
      case 'Fahrenheit':
        this.celsiusToFahrenheitConversion();
        break;
      case 'Kelvin':
        this.celsiusToKelvinConversion();
        break;
      case 'Rankine':
        this.celsiusToRankineConversion();
        break;
    }
    break;
  case 'Fahrenheit':
    break;
  case 'Rankine':
    break;
  case 'Kelvin':
    break;
}

However, keep in mind that these conversions are based on mathematical formulas. For example, converting Fahrenheit to Celsius involves the formula (32°F − 32) × 5/9, Fahrenheit to Kelvin is (32°F − 32) × 5/9 + 273.15, and Fahrenheit to Rankine is 32°F + 459.67. Since math follows a systematic approach, creating a conversion table as an object with lookup values could be a more organized way of handling this:

const magicalLookupTable = {
  celsius: {
    fahrenheit: () => {
      /** Implementation */
    },
    kelvin: () => {
      /** Implementation */
    }
  },
  fahrenheit: {
    celsius: () => {
      /** Implementation */
    },
    kelvin: () => {
      /** Implementation */
    }
  }
}

Answer №2

Upon observing this, I notice a combination of keys paired with function values.

An alternative approach to illustrate this concept is through the use of a standard object where the keys represent the combinations and correspond to specific functions:

const conversionMethods = {
    'miles-kilometers': this.milesToKilometersConversion,
    'pounds-kilograms': this.poundsToKilogramsConversion,
    'inches-centimeters': this.inchesToCentimetersConversion
};

const combinedKey = `${this.inputType.toLowerCase()}-${this.targetType.toLowerCase()}`;
const calculation = conversionMethods[combinedKey];

calculation();

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

reconfigure keyboard shortcuts in web browser

In the popular web browser Google Chrome, users can quickly jump to the next tab by pressing CTRL + TAB. Is there a way to change or disable this shortcut? The provided code snippet does not seem to work as intended. $(document).keydown(function(e){ ...

Best practices for extending the Array<T> in typescript

In a discussion on extending the Static String Class in Typescript, I came across an example showing how we can extend existing base classes in typescript by adding new methods. interface StringConstructor { isNullOrEmpty(str:string):boolean; } String. ...

Perform an Angular HTTP request and await responses from multiple sources

I'm currently working with Angular 11 and looking to make an HTTP call to an API that will trigger a server-side process. Here's the code for the HTTP call: processData(data) { return this.httpClient.post('https://myurl/api/process&apos ...

What is the best way to update only a portion of a nested schema in mongoose?

UPDATE: Through numerous trials, I finally discovered a successful method that converts any object into a format that mongoose can interpret. Take a look at the solution provided here: const updateNestedObjectParser = (nestedUpdateObject) => { cons ...

Mongoose's hook function is effective in the pre-stage but ineffective in the post-stage

When using Mongoose hooks, I aim to automatically change the status property to false if the outstandingBalance property has a value of zero. Although attempting to achieve this with Mongoose's PRE hook works, it requires re-invoking the request afte ...

Implementing a JavaScript function that directs to the current page

I have set up my index page with a link that looks like this: <li onClick="CreateUser()"> <a href="#CreateUser">CreateUser</a> </li> When the "Create User" list item is clicked, the main page content is populated as follows: fun ...

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

Create a new tab that is active and use ng-repeat in the uib-tab directive

I've been trying to solve this problem for a while now. I came across a similar post, but it was left unanswered. So, I decided to create my own post with a Plunkr example. The issue I'm facing is that upon loading, the ui-tab always defaults to ...

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...

Displaying an IP camera feed on a three.js canvas

I've been presented with a seemingly straightforward task in JavaScript that I'm not very familiar with. The challenge is to take an IP camera stream and display it on a three.js canvas. To start, I came across an example that uses a webcam inst ...

Matching names with corresponding IDs from multiple arrays in React

In my React app, I am dealing with an array structure. There is one array that contains the ids of two other arrays, along with their respective names. The goal is to create a new array that combines all the necessary information. Here is a simplified vers ...

I am having trouble retrieving the group attribute from the FormBuilder within my reactive form in React

Issue with 'group' property in 'FormBuilder' type See below for the code snippet import { FormBuilder, FormGroup, Validators } from '@angular/forms'; export class LoginPageForm{ constructor(private formBuilder = FormBuild ...

Exploring the world of jQuery AJAX alongside Google's currency calculator

I'm currently working on a code that utilizes an AJAX call to access the Google currency calculator. The expected outcome is to receive a JSON array that can then be used to gather exchange rate data. Here is the link: http://www.google.com/ig/cal ...

Launching a modal using a method in Vue.js that includes constantly changing content

I am currently developing a feature in my VueJs component that involves opening a modal when a certain condition becomes true, and then retrieving data from a controller to display in the modal. After searching online, I have not been able to find clear i ...

Fundamentals of Angular 2

It's not just an inconvenience, but something that truly frustrates me. Could someone please clarify the following: Why does Angular load these scripts in HTML directly from node_modules https://i.sstatic.net/D8UrG.png Why am I unable to simply imp ...

What causes the generation of an outdated object when utilizing the let and new keywords to create a new object within a service function?

Hey there, looking for a basic auth authentication service in angular2? Here's the issue I'm facing: When a user logs in for the first time, everything works smoothly. However, if they try to log in with a different account for the second time, ...

Why is TypeScript resorting to using 'any' for specific prop type definitions in React?

Having some trouble with my props typing: export interface ITouchable { isDisabled?: boolean; margin?: Margin; height?: number; bgColor?: string; } The definition of Margin is as follows: type Margin = | { top?: number; bottom?: nu ...

Angular 6: Inconsistent performance of [(ngModel)] functionality

In my Angular 6 project, I am utilizing Bootstrap Modals to implement a specific functionality. Upon clicking the modify button, a modal window should appear with pre-filled values. https://i.sstatic.net/PIg0L.jpg Although I am using template-driven form ...

Ways to prevent users from being redirected when they press the back button on a webpage

Similar Question: How can I prevent the back button from working in IE and Firefox? I'm currently working on a single page website (DAM) that requires user authentication to enter. After logging in, if a user clicks the back button, they are dire ...

Plane flying above a Box in ThreeJs

Encountering an issue where a plane placed over a box disappears at certain camera angles. It seems like the problem is related to the box's polygons, but the exact cause is unknown. You can view an example here: http://jsfiddle.net/fv9sqsoj/9/ var ...