Vivek
Vivek

Reputation: 61

Looking to optimize a typescript function

I am trying for opportunities to optimize the below typescript function. Need some advise on the same.

I tried to optimize the

return {
            'customer.account.personType': personType,
            'customer.loginUsrType': loginUsrType,
            'customer.login.userLogged': preference
        };

block, However, the code was not easy to read.

fetchUserDetails(){
    const response = service.fetchResp();
    const isUservalid = UserUtils.isUservalid();
    const isUsrpresent = service.isUsrpresent();
    let loginUsrType: string;
    let preference: string;
    let personType: string = '';
    const detailResp = response & response.detailResp;
    loginUsrType = isUservalid ? 'MBS' : 'CONT';
    if (isUsrpresent) {
        preference = isUservalid ? 'MBS' : 'CONT';
    }
    if (!!detailResp && isUservalid) {
        personType = 'PTU';
    } else if (!!detailResp && !isUservalid) {
        personType = 'IPU';
    } else {
        personType = 'CONT';
    }
    if (!!preference) {
        return {
            'customer.account.personType': personType,
            'customer.loginUsrType': loginUsrType,
            'customer.login.userLogged': preference
        };
    } else if (!!loginUsrType) {
        return {
            'customer.loginUsrType': loginUsrType
        }
    } else (!loginUsrType) {
        return {
            'customer.account.personType': personType,
            'customer.loginUsrType': loginUsrType
        }
    }
}

Thanks in advance.

Upvotes: 1

Views: 279

Answers (1)

Kamil Naja
Kamil Naja

Reputation: 6682

This function is doing to much things at once, the best way to optimise, is create multiple smaller functions. Some pseudo-ts to show idea:

type Customer = {
  account: Account,
  loginUsrType: LoginUsrType,
  userLogged: boolean
}
// this is good candidate for new fn
const getCustomer = (preference?: PreferenceType, loginUsrType?: boolean, customer: Customer): Customer => {
if (!!preference) {
        return {
            customer.account.personType: personType,
            customer.loginUsrType: loginUsrType,
            customer.login.userLogged: preference
        };
    } else if (!!loginUsrType) {
        return { // you can use spread operator to operate on copy of object
            ...customer,
            loginUsrType // no need do type : loginUserType again
        }
    } else if(!loginUsrType) {
        return {
            ...customer,
            personType,
            loginUsrType
        }
    } else {
        return
}
}

Upvotes: 2

Related Questions