SOURCE

/*
获取 随机红包金额
_redPackage:{ remainSize 剩余的红包数量,remainMoney 剩余的钱(元) }
*/
const MINMONEY = 0.01
const shuffle = (arr = []) => {
  let len = arr.length
  while (len > 1) {
    const index = Math.floor(Math.random() * len--);
    [
  arr[len],
  arr[index]
] = [
  arr[index],
  arr[len]
]
  }
  return arr
}
const getRandomMoneyByPackage = function (_redPackage) {
  if (_redPackage.remainMoney <= 0 || _redPackage.remainSize < 1) {
    return 0
  }
  if (_redPackage.remainSize === 1) {
    _redPackage.remainSize--
    return Math.round(_redPackage.remainMoney * 100) / 100
  }
      // Random r     = new Random();
  let min = _redPackage.min || MINMONEY //
  let max = _redPackage.remainMoney / _redPackage.remainSize * 2
  let money = Math.random() * max
  money = money <= min ? min : money
  money = Math.floor(money * 100) / 100
  _redPackage.remainSize--
  _redPackage.remainMoney -= money
  // 返回单位:元
  return money
}
/*
getRandomMoney
totalAmount: 红包总额(分)
redpackNumber: 红包总数(个)
limit:红包最小值(分)
debug:是否打印调试信息,0不打印,1打印
*/
function getRandomMoney (totalAmount, redpackNumber, limit = 1, debug = 0) {
  totalAmount = +(totalAmount / 100).toFixed(2)
  limit = +(limit / 100).toFixed(2)
  if (redpackNumber < 1) {
    throw new Error('红包个数最少为1个')
  }
  if (totalAmount / redpackNumber < limit) {
    throw new Error(`平均每个红包最少 ${limit} 元`)
  }
  let remainMoney = totalAmount - limit * redpackNumber
  console.log('remainMoney: ', remainMoney)
  if (remainMoney === 0) {
    const perFen = parseInt(limit * 100)
    const results = Array(redpackNumber).fill(perFen)
    if (debug) {
      console.log(`每个红包金额相同:¥${limit},即 ${perFen} 分`)
      console.log('结果(分):', results)
    }
    return results
  }

  const redPackage = { remainSize: redpackNumber, remainMoney: remainMoney, min: 0.01 }
  let results = []
  for (var i = 0; i < redpackNumber; i++) {
    let money = getRandomMoneyByPackage(redPackage)
    results.push(money)
  }
  results = shuffle(results)
  const resultsYuan = results.map(res => +(res + limit).toFixed(2))
  const resultsFen = resultsYuan.map(res => parseInt((res * 100).toFixed(0)))
  if (debug) {
    console.log(`总金额:¥${totalAmount},${redpackNumber} 个红包,每个红包最低¥${limit}`)
    console.log('结果(元):', resultsYuan)
    console.log('结果(分):', resultsFen)
    const reducer = (accumulator, item) => {
      return accumulator + item
    }
    const totalYuan = resultsYuan.reduce(reducer)
    console.log('总和(元): ', +totalYuan.toFixed(2))
    const totalFen = resultsFen.reduce(reducer)
    console.log('总和(分): ', totalFen)
  }

  return resultsFen
}


const totalAmountFen = 7 * 100
const redpackNumber = 6
const limitFen = 1 * 100
const debug = 1
let result = getRandomMoney(totalAmountFen, redpackNumber, limitFen, debug)
console.log(result)
console 命令行工具 X clear

                    
>
console