计算状态数-重构

时间:2018-12-15 21:07:41

标签: javascript node.js

我实现了一个逻辑,可以通过data变量来计算剩余的数量和成本。它循环遍历每个产品,并通过计算Returned个状态的数量来计算剩余的剩余数量,并减去产品数量。

有没有一种方法可以重构此代码,使其看起来更清晰,可理解/可维护?我不喜欢必须执行以下操作:obj[productItem.ProductId]看起来有点难看。

const data = {Products: [{ProductId: 123,Qty: 5,Price: 50,State: [{Name: "Returned",Qty: 1},{Name: "Returned",Qty: 3}]},{ProductId: 123,Qty: 2,Price: 20,State:[{Name: "Returned",Qty: 1}]}]};


function getRemainingQty(order) {
    return order.Products.reduce((obj, productItem) => {
      let productStates = [];
  
      if (productItem.State) {
        productStates = productItem.State;
      }
      
      let returnedQty = productStates.reduce((quantity, productState) => {
        return productState.Name === "Returned" ? quantity + productState.Qty : quantity;
      }, 0);
  
      let returnRemainingQty = productItem.Qty - returnedQty;
      let returnAmountCost =  productItem.Price / productItem.Qty * returnRemainingQty;
  
      if (obj[productItem.ProductId]) {
        obj[productItem.ProductId].QtyRemaining += returnRemainingQty;
        obj[productItem.ProductId].ReturnCostRemaining += returnAmountCost;
      } else {
        obj[productItem.ProductId] = {
          QtyRemaining: returnRemainingQty,
          ReturnCostRemaining: returnAmountCost
        };
      }
  
      return obj;
    }, {});
  }


  console.log(getRemainingQty(data));

1 个答案:

答案 0 :(得分:1)

以下是使用解构,布尔||filter,...的一些想法:

const data = {Products: [{ProductId: 123,Qty: 5,Price: 50,State: [{Name: "Returned",Qty: 1},{Name: "Returned",Qty: 3}]},{ProductId: 123,Qty: 2,Price: 20,State:[{Name: "Returned",Qty: 1}]}]};

function getRemainingQty(order) {
    return order.Products.reduce((obj, { ProductId, Qty, Price, State } ) => {
        const returnedQty = (State || [])
              .filter(({ Name }) => Name === "Returned")
              .reduce((quantity, { Qty }) => quantity + Qty, 0);      
        const productStock = obj[ProductId] || (obj[ProductId] = {
            QtyRemaining: 0,
            ReturnCostRemaining: 0
        });
        const returnRemainingQty = Qty - returnedQty;
        productStock.QtyRemaining += returnRemainingQty;
        productStock.ReturnCostRemaining += Price / Qty * returnRemainingQty;
        return obj;
    }, {});
}

console.log(getRemainingQty(data));