From 2224e9c00f544f9c4dde3258ed02113321eb29ce Mon Sep 17 00:00:00 2001 From: Luk Lu Date: Tue, 22 Mar 2022 14:33:24 +0800 Subject: [PATCH] add function randomNumber --- index.js | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index ab61331..f7205e2 100644 --- a/index.js +++ b/index.js @@ -117,6 +117,22 @@ module.exports = { return parseInt(port) }, + randomNumber ({ length, min, max } = {}) { + // 长度为 length 的随机数字,或者 (min||0) <= num < max + var num = 0 + if (typeof length === 'number' && length > 0) { + num = parseInt(Math.random() * Math.pow(10, length)) + num = num.toString().padStart(length, '0') + } else if (typeof max === 'number' && max > 0) { + min = typeof min === 'number' && min >= 0 ? min : 0 + num = parseInt(Math.random() * (max - min)) + min + } else { + // 如果 option 为空 + num = Math.random() + } + return num + }, + /** * 用户编号转邀请码 * @@ -125,7 +141,7 @@ module.exports = { * @return {*} * @memberof TICrypto */ - aiid2regcode(aiid) { + aiid2regcode (aiid) { const alphabet = 'e5fcdg3hqa4b1n0pij2rstuv67mwx89klyz' const base = 16367 let num = (aiid + base) * (base - alphabet.length) @@ -147,7 +163,7 @@ module.exports = { * @return {*} * @memberof TICrypto */ - regcode2aiid(code) { + regcode2aiid (code) { if (typeof code === 'string' && /^[a-zA-Z0-9]+$/.test(code)) { const alphabet = 'e5fcdg3hqa4b1n0pij2rstuv67mwx89klyz' const base = 16367