清理功能

时间:2019-10-18 01:20:45

标签: javascript function

所以,伙计们,我有一个奇怪的问题... 我有以下代码:

var valuesForLakewood = (function (m, k) { 
      return m[k] === undefined ? null : m[k]; 
    })(this.lakewood, customerType);
    var valuesForBridgewood = (function (m, k) { 
      return m[k] === undefined ? null : m[k]; 
    })(this.bridgewood, customerType);
    var valuesForRidgewood = (function (m, k) { 
      return m[k] === undefined ? null : m[k]; 
    })(this.ridgewood, customerType);
    lakewoodCost = weekdays * valuesForLakewood[0] 
      + weekends * valuesForLakewood[1];
    bridgewoodCost = weekdays * valuesForBridgewood[0] 
      + weekends * valuesForBridgewood[1];
    ridgewoodCost = weekdays * valuesForRidgewood[0] 
      + weekends * valuesForRidgewood[1];
    var hotel = 
      this.minCost(lakewoodCost, bridgewoodCost, ridgewoodCost);

我只需要清理一点。我一遍又一遍地重复相同的功能,我希望您能就如何清理这一点,以减少代码的大小发表意见。有什么想法吗?提前致谢!

1 个答案:

答案 0 :(得分:0)

使用单个函数从对象中提取值,而不是六个独立变量,而是两个数组,进行解构以使总成本操作更易于理解,然后将所得数组扩展到minCost中:

const getVal = obj => obj[customerType] === undefined ? null : obj[customerType];
const values = [this.lakewood, this.bridgewood, this.ridgewood].map(getVal);
const costs = values.map(([weekdayCost, weekendCost]) => weekdays * weekdayCost + weekends * weekendCost);
const hotel = this.minCost(...costs);