-
Notifications
You must be signed in to change notification settings - Fork 4
/
validate-lottery.js
73 lines (67 loc) · 2.02 KB
/
validate-lottery.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function lottery (firstPrize = 1, secondPrize = 2, thirdPrize = 3) {
// 先驗證輸入參數
if (!validateInput(firstPrize, secondPrize, thirdPrize)) {
return;
}
// 取得最長小數點
let tmp = [firstPrize, secondPrize, thirdPrize];
let longest = 0;
tmp.forEach((prize) => {
let afterPoint = prize.toString().split(".")[1];
if (afterPoint) {
if (afterPoint.length > longest) {
longest = afterPoint.length;
}
}
});
// 讓機率變整數
let multiple = Math.pow(10, longest);
// 沒有用 Math.floor 會出現 js 小數點結尾的 Bug,ex:11100.000000000002
firstPrize = Math.floor(firstPrize * multiple);
secondPrize = Math.floor(secondPrize * multiple);
thirdPrize = Math.floor(thirdPrize * multiple);
// 籤筒的總數量
let max = multiple * 100;
let luckyBox = [];
// 放入籤筒
for (var i = 0; i < max; i++) {
if (firstPrize !== 0) {
luckyBox.push("一獎");
firstPrize--;
} else if (secondPrize !== 0) {
luckyBox.push("二獎");
secondPrize--;
} else if (thirdPrize !== 0) {
luckyBox.push("三獎");
thirdPrize--;
} else {
luckyBox.push("感謝獎");
}
}
// 抽獎
console.log(luckyBox[Math.floor(Math.random() * (max - 1))]);
}
function validateInput (firstPrize, secondPrize, thirdPrize) {
// 確認是否為正數
var reg = /^(?=.+)(?:[1-9]\d*|0)?(?:\.\d+)?$/;
if (!(reg.test(firstPrize) && reg.test(secondPrize) && reg.test(thirdPrize))) {
console.log("請確認輸入參數皆為正數!");
return false;
}
// 確認沒爆表
if (firstPrize + secondPrize + thirdPrize > 100) {
console.log("中獎機率超過 100 %,爆表了!");
return false;
}
return true;
}
const argsArray = [
[100, 2.34, 3.567], //中獎率不可能超過100
[-1, 2.34, 3.567], //機率不可為負
[1, "錯誤", 3.567], //機率不可含有文字
[1, 2.34, 3.567],
];
argsArray.forEach((args) => {
console.log("驗證: " + args);
console.log(validateInput.apply(this, args));
});