Home > front end >  How to optimize if statements from multiple services?
How to optimize if statements from multiple services?

Time:08-25

Been trying to refactor several if statements to avoid a large file but, I'm wondering if I can get a little help.

I have these lines of code where it checks if it's 'text1', 'text2'... and so on. Then it evaluates depending of the authorization his specific service:

    if (authorization === 'text1') {
        const currUser = this.text1Service.currUser();
        if (currUser) {
            return true;
        }
    }
    
    if (authorization === 'text2') {
        const currUser = this.text2Service.currentUserValue;
        if (currUser) {
            return true;
        }
    }

    if (authorization === 'text3') {
        const currUser = this.text3Service.currUserValue;
        if (currUser) {
            return true;
        }
    }

Maybe I could set a variable with all the texts like texts = ['text1', 'text2', 'text3', 'text4'...] and check if authorization.includes(texts).

And making a method to pass the parameter of the currUser because in all the cases returns true if the service works, otherwise do nothing. The thing is to differentiate the service to use and I'm kinda lost.

Please guide me to the good practices if someone wants.

CodePudding user response:

One possible solution could be to use a dictionary object with current user strategies:

const currentUserServices = {
  text1: () => !!this.text1Service.currUser(),
  text2: () => !!this.text2Service.currentUserValue,
  text3: () => !!this.text3Service.currUserValue,
}

const service = currentUserServices[authorization]
return service()
  • Related