如何重写该函数,以便它将返回将在外部范围中重写的对象?

时间:2019-03-21 08:37:01

标签: javascript arrays node.js function

我正在尝试编写具有以下逻辑的彩票应用程序:

  1. 用户插入一个由6个数字和抽奖次数组成的数组。
  2. API接收信息并执行以下步骤:
    • 在每次平局中生成一个中奖阵列;
    • 将获胜的阵列与用户阵列进行比较;
    • 将结果推入一个新数组,该数组将计算正确数字的数量 更新用户奖赏(充值);

现在,我不知道该如何重写函数,因此它将接收两个数组,将它们进行比较,并用获胜的金额更新对象,并生成一个结果数组。

我试图在函数内部创建一个单独的对象-失败。

看起来每次函数调用时我的全局对象都会被重写

这是我的代码:

const LotteryController = {
  simulate: (req, res) => {
    const { numbers, draws } = req.body;
    let winArray;

    InputValidation(numbers, draws);

    const spentMoney = 5 * draws;
    let userResults;

    // Counting the number of winning numbers in the ticket, adding that number to the array
    const numbersCounter = function numbersCounter(userArr, winArr) {
      let counter = 0;
      const results = {
        wonMoney: 0,
        winNumArray: [0, 0, 0, 0, 0, 0, 0],
      };
      for (let i = 0; i < userArr.length; i += 1) {
        if (winArr.includes(userArr[i])) {
          counter += 1;
        }
      }
      switch (counter) {
        case 0:
          results.winNumArray[0] += 1;
          break;
        case 1:
          results.wonMoney += 5;
          results.winNumArray[1] += 1;
          break;
        case 2:
          results.wonMoney += 10;
          results.winNumArray[2] += 1;
          break;
        case 3:
          results.wonMoney += 28;
          results.winNumArray[3] += 1;
          break;
        case 4:
          results.wonMoney += 775;
          results.winNumArray[4] += 1;
          break;
        case 5:
          results.wonMoney += 55000;
          results.winNumArray[5] += 1;
          break;
        case 6:
          results.wonMoney += 25000000;
          results.winNumArray[6] += 1;
          break;
        default:
          throw new Error('Request is invalid');
      }

      return results;
    };

    for (let i = 1; i <= draws; i += 1) {
      // Generating a random array of 6 numbers

      // let winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53));
      // winArray = [...new Set(winArray)];

      winArray = new Set();
      while (winArray.size < 6) winArray.add(Math.floor(Math.random() * 53));
      winArray = Array.from(winArray);

      userResults = numbersCounter(numbers, winArray);
      console.log(userResults);
    }

    const responseObject = {
      input: {
        numbers,
        draws,
      },
      results: {
        spent: spentMoney,
        won: userResults.wonMoney,
        matches: userResults.winNumArray,
      },
    };

    ApiResponse.success(res, responseObject);
  },
};

0 个答案:

没有答案