UNPKG

js-red-package

Version:

用 js 实现一个类似微信红包的随机算法

174 lines (138 loc) 3.86 kB
# js-red-package 🧧 用 js 实现一个类似微信红包的随机算法 > 🚀 支持 JavaScript 浮点数运算 https://www.npmjs.com/package/js-red-package/ https://github.com/xgqfrms/js-red-package ## install ```sh $ yarn add js-red-package # or $ npm i js-red-package ``` ## usage ```js // ESM,build/index.min.mjs (default) import {autoRandomRedPackage} from "js-red-package"; // OR // CMJ, build/index.min.js const autoRandomRedPackage = require("js-red-package"); // const autoRandomRedPackage = require("js-red-package/build/index.min.js"); ``` ## test ```js const total = arr => arr.result.reduce((acc, i) => acc += i*100, 0) / 100; // 测试 test cases const test = autoRandomRedPackage(0.1, 11);// ❌ 异常处理 const test0 = autoRandomRedPackage(0.1, 5); const test1 = autoRandomRedPackage(0.1, 10); // ✅ ok const test2 = autoRandomRedPackage(1, 10); const test3 = autoRandomRedPackage(10, 10); const test4 = autoRandomRedPackage(100, 10); const test5 = autoRandomRedPackage(100, 11); log(`\ntest =`, test); log(`total =`, test && total(test)); log(`\ntest =`, test0); log(`total =`, test0 && total(test0)); log(`\ntest =`, test1); log(`total =`, test1 && total(test1)); log(`\ntest =`, test2); log(`total =`, test2 && total(test2)); log(`\ntest =`, test3); log(`total =`, test3 && total(test3)); log(`\ntest =`, test4); log(`total =`, test4 && total(test4)); log(`\ntest =`, test5); log(`total =`, test5 && total(test5)); /* $ node test.js (node:2259) ExperimentalWarning: The ESM module loader is experimental. 💩 请重新输入红包数量! 减少红包数量,或增加红包金额! ❌ 你输入的红包数量太多了,每个人至少要能分到 0.01 元! test = false total = false test = { total: 0.1, result: [ 0.02, 0.01, 0.02, 0.03, 0.02 ], desc: '\n' + ' 🕵️‍♂️ 你输入的红包总额是 0.1 元, 红包数量是 5 个!\n' + ' 👍 最大的红包是 0.03 元!\n' + ' 👎 最小的红包是 0.01 元!\n' + ' ' } total = 0.1 test = { total: 0.1, result: [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 ], desc: '\n' + ' 🕵️‍♂️ 你输入的红包总额是 0.1 元, 红包数量是 10 个!\n' + ' 👍 最大的红包是 0.01 元!\n' + ' 👎 最小的红包是 0.01 元!\n' + ' ' } total = 0.1 test = { total: 1, result: [ 0.18, 0.08, 0.09, 0.12, 0.01, 0.18, 0.07, 0.08, 0.14, 0.05 ], desc: '\n' + ' 🕵️‍♂️ 你输入的红包总额是 1 元, 红包数量是 10 个!\n' + ' 👍 最大的红包是 0.18 元!\n' + ' 👎 最小的红包是 0.01 元!\n' + ' ' } total = 1 test = { total: 10, result: [ 0.76, 0.39, 1.88, 0.71, 0.33, 1.57, 0.55, 1.23, 1.72, 0.86 ], desc: '\n' + ' 🕵️‍♂️ 你输入的红包总额是 10 元, 红包数量是 10 个!\n' + ' 👍 最大的红包是 1.88 元!\n' + ' 👎 最小的红包是 0.33 元!\n' + ' ' } total = 10 test = { total: 100, result: [ 11.34, 13.3, 9.6, 3.29, 10.27, 12.1, 12.31, 5.17, 6.29, 16.33 ], desc: '\n' + ' 🕵️‍♂️ 你输入的红包总额是 100 元, 红包数量是 10 个!\n' + ' 👍 最大的红包是 16.33 元!\n' + ' 👎 最小的红包是 3.29 元!\n' + ' ' } total = 100 test = { total: 100, result: [ 10.43, 15.55, 9, 4.64, 7.74, 11.96, 12.9, 4.82, 14.19, 8.36, 0.41 ], desc: '\n' + ' 🕵️‍♂️ 你输入的红包总额是 100 元, 红包数量是 11 个!\n' + ' 👍 最大的红包是 15.55 元!\n' + ' 👎 最小的红包是 0.41 元!\n' + ' ' } */ ```