【问题标题】:how to reduce the complexity of this code which has if else [closed]如何降低此代码的复杂性,如果有 else [关闭]
【发布时间】:2022-12-06 00:49:14
【问题描述】:

如何使下面的代码更简单?

这段代码中有一个if-else循环,但是能不能减少到最少的行数呢?

我们可以做些什么来降低这段代码的复杂性?

let android_devices = '';
    let ios_devices = '';
    let web_devices = '';
    if (location_id == '') {
      android_devices = await PRISMA.customers.count({
        where: {
          channel: 'ANDROID',
          ref: headerData?.ref,
        },
      });
      ios_devices = await PRISMA.customers.count({
        where: {
          channel: 'IOS',
          ref: headerData?.ref,
        },
      });
      web_devices = await PRISMA.customers.count({
        where: {
          channel: 'WEBSITE',
          ref: headerData?.ref,
        },
      });
    } else {
      android_devices = await PRISMA.customers.count({
        where: {
          channel: 'ANDROID',
          ref: headerData?.ref,
          location_id: location_id,
        },
      });
      ios_devices = await PRISMA.customers.count({
        where: {
          channel: 'IOS',
          ref: headerData?.ref,
          location_id: location_id,
        },
      });
      web_devices = await PRISMA.customers.count({
        where: {
          channel: 'WEBSITE',
          ref: headerData?.ref,
          location_id: location_id,
        },
      });
    }

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您至少可以做几件事:

    1. 根据location_id是否为"",将变量设置为等于location_idheaderData?.ref,然后在count调用中重用它。这样做会将代码减半,使其更易于维护:

      const ref = location_id == "" ? headerData?.ref : location_id;
      let android_devices = await PRISMA.customers.count({
          where: {
              channel: "ANDROID",
              ref,
          },
      });
      let ios_devices = await PRISMA.customers.count({
          where: {
              channel: "IOS",
              ref,
          },
      });
      let web_devices = await PRISMA.customers.count({
          where: {
              channel: "WEBSITE",
              ref,
          },
      });
      
    2. 使用mapPromise.all查询计数,然后通过iterable destructuring将它们分配给变量。 (还有另一种类型,即对象解构,但为此我们需要可迭代的解构。)像这样:

      像这样:

      const ref = location_id == "" ? headerData?.ref : location_id;
      let [android_devices, ios_devices, web_devices] = await Promise.all(
          ["ANDROID", "IOS", "WEBSITE"].map((channel) => PRISMA.customers.count({
              where: {
                  channel,
                  ref,
              },
          })
      ));
      

      请注意,对于我们调用 map 的耳阵列以及我们分配的变量以相同的顺序排列是很重要的。 (Promise.all 保留顺序,因此我们知道我们为 "ANDROID" 请求的计数将位于结果的索引 0 处。)

    【讨论】:

    • (糟糕,#1 中的编辑错误。如果您在对 count 的调用中仍然看到 headerDaa?.ref,请点击刷新。)
    猜你喜欢
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多