I am looking to abstract a TypeScript function

Looking for advice on how to generalize a TypeScript method. Here's my current approach - I want to find a way to reduce the amount of code in this method.

function getAuthProvider(authProvider) {
    let provider;

    switch (authProvider) {
        case 'google':
            provider = new firebase.auth.GoogleAuthProvider();
            break;
        case 'facebook':
            provider = new firebase.auth.FacebookAuthProvider();
            break;
        case 'twitter':
            provider = new firebase.auth.TwitterAuthProvider();
            break;
        case 'microsoft':
            provider = new firebase.auth.OAuthProvider('microsoft.com');
            provider.setCustomParameters({ tenant: 'b7773erqqqfr5678' });
            break;
        default:
            provider = null;
    }

    return provider;
}
Is there a more efficient way to write this method?

Answer №1

If you want to simplify the conditions, you can use ternary operators in your code like this:

someFunc() {
  const provider = authProvider === 'google' 
    ? new firebase.auth.GoogleAuthProvider()
    : authProvider === 'facebook'
      ? new firebase.auth.FacebookAuthProvider()
      : new firebase.auth.TwitterAuthProvider();
  
  provider.setCustomParameters({ prompt: 'select_account' });
  return provider;
}

Latest Update

someFunc() {
  const provider = authProvider === 'google'
    ? { provider: new firebase.auth.GoogleAuthProvider() }
    : authProvider === 'facebook'
      ? { provider: new firebase.auth.FacebookAuthProvider() }
      : authProvider === 'twitter'
        ? { provider: new firebase.auth.TwitterAuthProvider() }
        : { provider: new firebase.auth.OAuthProvider('microsoft.com'), tenant: 'b7773erqqqfr5678' }

  (!!provider.tenant)
    ? provider.provider.setCustomParameters({ tenant: provider.tenant })
    : provider.provider.setCustomParameters({ prompt: 'select_account' })

  return provider.provider;
}

Answer №2

Why not try using a switch case instead of nested conditions?

         let authProvider;
         let provider;

         switch(authProvider) {
        
         case 'google':
           provider = new firebase.auth.GoogleAuthProvider();
           break;
         case 'facebook':
           provider = new firebase.auth.FacebookAuthProvider();
           break;
         case 'twitter':
           provider = new firebase.auth.TwitterAuthProvider();
           break;
         case 'microsoft':
           provider = new firebase.auth.OAuthProvider('microsoft.com');
           break;
        }
        
        provider.setCustomParameters({
                prompt: 'select_account'
              });
         return provider;

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

You must include the formControlName within a parent formGroup directive

Upon creating a model-driven form, an error is encountered: Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). ...

What is the best way to execute a sequence of http requests only after the previous one has been completed successfully, while also addressing any

Working with Angular/rxjs 6 has brought me to a challenge. I'm struggling to get an observable sequence to run smoothly as intended. Here's the concept of what I'm trying to achieve: Request received to change systems: Check permissions Fe ...

What is the importance of having a reference path for compiling an AngularJS 2 project using gulp-typescript?

I wanted to modify the Angular Tour Of Heros project to utilize gulp from this Github Repository. This is the gulpfile.json file I came up with: const gulp = require('gulp'); const del = require('del'); const typescript = require(&apo ...

How can I transform a mat-list into a dropdown menu in Angular?

I recently used Angular to create a list using mat-list. Here is the code I implemented: <mat-list style="display: inline-grid;"> <mat-list-item *ngFor="let item of item"> <mat-checkbox [(ngModel)] ...

Filtering FieldSelector options in react-querybuilder: A step-by-step guide

I am currently working on a task to eliminate the fields from FieldSelector that have already been utilized. In my custom FieldSelector component, let's assume there are fields A, B, C, D, E available. If A & B have been used, they should not be ...

Error: Unable to access the 'visitStatement' property of an undefined object within Angular 2

Help! I encountered an error in my angular2 application. The error message says: TypeError: Cannot read property ‘visitStatement’ of undefined ...

Encountering issues with Angular 4 routing functionality in production environment

Everything seems to be functioning well with the routing in my Angular 4 web-app on my development setup, and the menu redirections are working smoothly in the live version. However, I have encountered an issue where the development version redirects to d ...

Determine whether or not there are any duplicate elements within an array object

Is there a way to determine true or false if there are any duplicates within an object array? arr = [ { nr:10, name: 'aba' }, { nr:11, name: 'cba' }, { nr:10, name: 'aba' } ] arr2 = [ { year:2020, cit ...

Issue with React Redux: Store dispatch not causing component update

I have recently implemented React Redux in my project, but I seem to be encountering some issues. Despite changing the state, the value remains the same. I attempted to use useStore(), but it does not take any parameters. Can anyone provide insight into wh ...

Tips for Verifying a User's Identity using Username and Password

After examining this Angular 2 solution: state: string = ''; error: any; constructor(public af: AngularFire, private router: Router) { this.af.auth.subscribe(auth => { if (auth) { this.router.navigateByUrl('/mem ...

What is the best way to compare two TypeScript object arrays for equality, especially when some objects may have multiple ways to be considered equivalent

Currently, I am in the process of developing a cost function for a game where players are given a set of resources in their hand. The resources can be categorized into different types such as Fire, Air, Water, Earth, Good, Evil, Law, Chaos, and Void. Thes ...

Dealing with the "this" problem in TypeScript and its impact on scope

Here is my code snippet: class MyClass { name = "MyClass"; // traditional method definition getName1(){ return this.name; } // method defined as an arrow function getName2 = () => { return this.name; ...

The Firebase Cloud Function is failing to trigger on the onCreate event within the Firebase Realtime Database

I recently deployed a function to Firebase with the following code: import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; console.log('FILE LOADED'); const serviceAccount = require(' ...

How to manually set the value of a select object in Angular 5

I am facing an issue with setting an object value manually for a select element. I have attempted to use setValue or patchValue with Object, but unfortunately, it did not yield the desired result. <mat-select placeholder="Selecione a resposta" (change) ...

What could be causing the malfunction of the dropdown menu attached to my button?

I've been working on setting up a simple button in my Angular application that should display a dropdown menu with various options when clicked. I copied and pasted some Bootstrap template code, made some modifications to match the style of my app, bu ...

Refreshing the Angular2 view upon asynchronous model changes

Looking at my Angular2 component, I see that it has a dependency on a datastore. In the template, there are some data bindings connected to that store, like "{{datastore.weather.curTemp}}". The datastore receives updates periodically through http requests. ...

Using Typescript to customize the color of Ionic's Ion-checkbox

I am attempting to modify the color of the ion-checkbox using TypeScript <ion-item > <ion-label id="check1">No</ion-label> <ion-checkbox color="blue" id="box1" [(ngModel)]="todo.check1" name="check1"></ion-checkbox&g ...

What is the correct way to construct an object in TypeScript while still taking types into account?

Hey, I'm having trouble implementing a common JavaScript pattern in TypeScript without resorting to using any to ignore the types. My goal is to write a function that constructs an object based on certain conditions and returns the correct type. Here& ...

What is the process for accessing and updating values within nested form fields in angular2?

I have been working on an Angular 2 application that utilizes Angular reactive forms. I need to retrieve the value of the innermost element and then update that value accordingly. form : FormGroup; constructor(private formBuilder: FormBuilder) { this. ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...