js實現微信搶紅包
阿新 • • 發佈:2018-12-22
金額隨機:額度在0.01和(剩餘平均值*2)之間。
/**
* 搶紅包
* @param {[number]} totalAmount [總金額]
* @param {[number]} totalPeople [總人數]
* @return {[Array]} [每個人搶到的金額]
*/
function assign(totalAmount, totalPeople){
var remainAmount = +totalAmount;
var remainPeople = +totalPeople;
var arr = [];
while (remainPeople > 0){
let num = scramble(remainAmount, remainPeople);
remainAmount = remainAmount - num;
remainPeople--;
arr.push(num);
}
return arr;
}
function scramble(remainAmount, remainPeople){
if(remainPeople === 1){
return +remainAmount.toFixed(2 );
}
let max = ((remainAmount / remainPeople) * 2 - 0.01).toFixed(2);
let min = 0.01;
let range = max - min;
let rand = Math.random();
let num = min + Math.round(rand * range); //四捨五入
return num;
}