Files
certd/packages/ui/certd-server/src/utils/random.ts
T

44 lines
1.0 KiB
TypeScript
Raw Normal View History

2024-10-03 22:03:49 +08:00
const numbers = "0123456789";
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const specials = "~!@#$%^*()_+-=[]{}|;:,./<>?";
2023-01-29 13:44:19 +08:00
/**
* Generate random string
* @param {Number} length
* @param {Object} options
*/
2024-08-28 14:40:50 +08:00
function randomStr(length, options?) {
2023-01-29 13:44:19 +08:00
length || (length = 8);
options || (options = {});
2024-10-03 22:03:49 +08:00
let chars = "";
let result = "";
2023-01-29 13:44:19 +08:00
if (options === true) {
chars = numbers + letters;
2024-10-03 22:03:49 +08:00
} else if (typeof options === "string") {
2023-01-29 13:44:19 +08:00
chars = options;
} else {
if (options.numbers !== false) {
2024-10-03 22:03:49 +08:00
chars += typeof options.numbers === "string" ? options.numbers : numbers;
2023-01-29 13:44:19 +08:00
}
if (options.letters !== false) {
2024-10-03 22:03:49 +08:00
chars += typeof options.letters === "string" ? options.letters : letters;
2023-01-29 13:44:19 +08:00
}
if (options.specials) {
2024-10-03 22:03:49 +08:00
chars += typeof options.specials === "string" ? options.specials : specials;
2023-01-29 13:44:19 +08:00
}
}
while (length > 0) {
length--;
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
export const RandomUtil = { randomStr };
2026-04-27 23:51:27 +08:00