我正在尝试编写具有以下逻辑的彩票应用程序:
现在,我不知道该如何重写函数,因此它将接收两个数组,将它们进行比较,并用获胜的金额更新对象,并生成一个结果数组。
我试图在函数内部创建一个单独的对象-失败。
(看起来每次函数调用时我的全局对象都会被重写)
这是我的代码:
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);
},
};