I want to assign a value to property when creating an object based on lot of conditions. Currently I'm using a separate function to get the value of the property, something like this:
function getLocationId(currency, storeCode, isBundle) {
if (currency === 'MYR') {
if (storeCode === 'store-1') {
return 1;
} else if (storeCode === 'store-2') {
return 2;
}
} else if (currency === 'SGD') {
if (storeCode === 'store-1') {
return 3;
} else if (storeCode === 'store-2') {
// This function can return the same value for a different condition
return 2;
} else if (!storeCode && !isBundle) {
return 8;
}
}
.
.
.
// More conditions, with some involving `isBundle`
}
function getAccountId(currency, storeCode, paymentMethod) {
// Function definition similar to getLocationId
// with checks for currency, storeCode, paymentMethod
}
function getRequestObject(event) {
return {
.
.
.
location: getLocationId(event.currency, event.storeCode, event.item.isBundle),
account: getAccountId(event.currency, event.storeCode, event.paymentMethod),
.
.
.
};
}
I feel like there are a lot of if...else constructs used with nested checks again. Is doing that even a good idea? Is there any design pattern I can use to build a request object with the right location ID and account ID based on the parameter event in getRequestObject?
PS: I'm not returning the integer value in the actual codebase, instead using this library called node-config and storing these IDs in a JSON file which I can later retrieve with config.get('propertyName').
A slightly cleaner approach without else statements after return statements.
function getLocationId(currency, storeCode, isBundle) {
if (currency === 'MYR') {
if (storeCode === 'store-1') return 1;
if (storeCode === 'store-2') return 2;
// other if or return a default value for this currency
}
if (currency === 'SGD') {
if (storeCode === 'store-1') return 3;
if (storeCode === 'store-2') return 2;
if (!storeCode && !isBundle) return 8;
}
}