有没有更好的方式编写这样的函数

时间:2019-10-17 20:05:19

标签: javascript

下面的函数带有两个参数,并返回一个对象数组。每个对象都应按照availableBagSizes数组的降序返回。 我举了两个例子,我想知道是否有更好的解决方案来实现相同的输出,以及为什么我的解决方案不好。

我需要第三个示例的帮助,该示例未按预期返回。

function getBagCounts(clientOrders, availableBagSizes) {
  // TODO: remove this hard-coded solution for test scenario
  // clientOrders === [9]

  // sorting the availablebag size in descending order
  const newAvailableBag = availableBagSizes.sort((a, b) => b - a);

  const result = [];
  let newRemainder;

  for (let index = 0; index < clientOrders.length; index++) {
    const clientOrder = clientOrders[index];

    // set the newremainder variable to clientOrder for the first loop
    newRemainder = index === 0 ? clientOrder : newRemainder;

    for (let j = 0; j < availableBagSizes.length; j++) {
      const bagSize = newAvailableBag[j];

      const count_result = Math.floor(newRemainder / bagSize);
      newRemainder = newRemainder % bagSize;
      const obj = {};

      if (newRemainder > bagSize) {
        result.push({ size: bagSize, count: 0 });
        continue;
      }

      // checking if it is the last item in the bagSizes
      if (j + 1 === availableBagSizes.length) {
        // setting the newreaminder to the next number of client order
        newRemainder = clientOrders[index + 1];
      }

      result.push({ size: bagSize, count: count_result });
    }
  }
  return result;
}

// first example
const clientOrders = [9];
const availableBagSizes = [1, 2, 4];
const expectedoutput = [
  { size: 4, count: 2 },
  { size: 2, count: 0 },
  { size: 1, count: 1 }
];

// second example
const clientOrders = [5, 12, 12];
const availableBagSizes = [1, 2, 4];
const expectedoutput = [
  { size: 4, count: 1 },
  { size: 2, count: 0 },
  { size: 1, count: 1 },
  { size: 4, count: 3 },
  { size: 2, count: 0 },
  { size: 1, count: 0 },
  { size: 4, count: 2 },
  { size: 2, count: 1 },
  { size: 1, count: 0 }
];

// third example
const clientOrders = [4.5];
const availableBagSizes = [1, 2, 4];
const expectedoutput = [
  { size: 4, count: 1 },
  { size: 2, count: 0 },
  { size: 1, count: 0.5 }
];

1 个答案:

答案 0 :(得分:0)

对我来说看起来不错。

如果想要好的代码,应该考虑性能和参数检查。

if (!Array.isArray(clientOrders) || !Array.isArray(availableBagSizes)) {
 return null;
}

另外,您应该尝试使用forEarch loop which is faster in performance

制作push的过程很慢,最好制作.map((element,index)=>{return null})

这实际上取决于您如何管理数据,但是我会说第一个循环是forEach,第二个循环是map。因为无论在第二个循环中发生什么情况,在您进行push的所有时间里,映射数组中都不会返回nullundefined