在根据大量条件创建对象时,我希望为属性分配一个值。目前,我正在使用一个单独的函数来获取属性的值,如下所示:
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),
.
.
.
};
}我觉得在嵌套检查中再次使用了很多if...else结构。这样做是个好主意吗?是否有任何设计模式可用于基于getRequestObject中的参数getRequestObject构建具有正确位置ID和帐户ID的请求对象?
PS:我不会在实际的代码库中返回整数值,而是使用这个名为node-config的库,并将这些in存储在一个JSON文件中,稍后我可以用config.get('propertyName')检索该文件。
发布于 2022-03-22 08:48:32
一种在else语句之后不使用return语句的稍微简洁的方法。
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;
}
}https://stackoverflow.com/questions/71568845
复制相似问题