【问题标题】:How do i reduce the complexity of THIS code我如何降低此代码的复杂性
【发布时间】:2022-12-07 13:03:54
【问题描述】:
graph_data_of_year = [ 0 0 0 0 0 0 0 0 0 0 0 120]

我在十二月份下了两个订单。在一个数组中,实际数量是60+60。代码工作正常,但我需要降低复杂性。实际金额数据类型为浮点数,输出应基于数组。每个月,它都会计算实际金额。 数据库:MONGODB ORM:棱镜

       let startofyear = MOMENT().startOf('year');
        let months_for_year = [];
        let year = []; // year
        for (let index = 0; index <= 11; index++) {
          const add1month = MOMENT(startofyear)
            .add(index, 'month')
            .format('YYYY-MM-DD' + 'T' + 'HH:mm:SS' + '.000+00:00');
          months_for_year.push(add1month);
        }
        for (let i = 0; i < months_for_year.length; i++) {
          let j = i + 1;
          let d = await PRISMA.orders.findMany({
            where: {
              created_at: {
                gte: months_for_year[i],
                lte:
                  i === months_for_year.length - 1
                    ? endOftheYear_date
                    : months_for_year[j],
              },
            },
            select: { actual_amount: true },
          });

          let total = 0;

          d.forEach((el) => {
            total += el.actual_amount;
            d.push(total);
          });
          year.push(d);
        }
        graph_data_of_year = year.map((el) => {
          if (el.length === 0) {
            return 0;
          } else {
            return el.pop();
          }
        });

        console.log(graph_data_of_year)

【问题讨论】:

  • 我看到有很多方法可以使它更小,也许更具可读性和美观性。我能看到的唯一实质性想法是使用 Promise.all() 同时执行所有 findMany
  • 你能把代码分享给我吗
  • 请注意,如果您的代码已经有效,那么 SO 是 not the right place to ask,您可能想寻求帮助以提高运行时复杂性,而不是 codereview

标签: javascript node.js


【解决方案1】:

这段代码实现了与原始代码相同的结果,但更简单易读。它使用一个循环来计算每个月的实际总金额,然后将图形数据设置为该值。它还使用更具描述性的变量名称,使代码更易于理解。

let startOfYear = MOMENT().startOf('year');
let monthsForYear = [];
let year = [];

// Create an array of dates representing the start of each month in the year
for (let index = 0; index <= 11; index++) {
  const add1Month = MOMENT(startOfYear).add(index, 'month').format('YYYY-MM-DDTHH:mm:SS.000+00:00');
  monthsForYear.push(add1Month);
}

// Get the actual amount for each month
for (let i = 0; i < monthsForYear.length; i++) {
  let j = i + 1;
  let d = await PRISMA.orders.findMany({
    where: {
      created_at: {
        gte: monthsForYear[i],
        lte: i === monthsForYear.length - 1 ? endOftheYear_date : monthsForYear[j],
      },
    },
    select: { actual_amount: true },
  });

  // Calculate the total actual amount for the month
  let total = 0;
  d.forEach((el) => {
    total += el.actual_amount;
  });
  year.push(total);
}

// Set the graph data to the calculated amounts
graphDataOfYear = year;

console.log(graphDataOfYear);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2022-12-06
    • 1970-01-01
    相关资源
    最近更新 更多