UNPKG

alpha-deca

Version:

A lightweight JavaScript library for generating random alphanumeric strings and characters

86 lines (78 loc) 2.35 kB
/** * Generates an array of alphanumeric characters including digits (0-9), * uppercase letters (A-Z), and lowercase letters (a-z). * * @returns {string[]} An array containing all alphanumeric characters * * @example * const chars = getAlphanumericChars(); * console.log(chars); // ['0', '1', '2', ..., '9', 'A', 'B', ..., 'Z', 'a', 'b', ..., 'z'] */ export function getAlphanumericChars() { const alphanumeric = []; for (let i = 48; i <= 57; i++) { alphanumeric.push(String.fromCharCode(i)); } for (let i = 65; i <= 90; i++) { alphanumeric.push(String.fromCharCode(i)); } for (let i = 97; i <= 122; i++) { alphanumeric.push(String.fromCharCode(i)); } return alphanumeric; } /** * Generates a random alphanumeric character. * * @returns {string} A single random alphanumeric character (0-9, A-Z, a-z) * * @example * const char = randomChar(); * console.log(char); // 'A', '5', 'z', etc. */ export function randomChar() { const alphanumeric = getAlphanumericChars(); return alphanumeric[Math.floor(Math.random() * alphanumeric.length)]; } /** * Generates a random string of specified length using alphanumeric characters. * * @param {number} length - The length of the string to generate * @returns {string} A random string of the specified length * * @example * const str = randomString(8); * console.log(str); // 'A7bK9mN2' * * @example * const shortStr = randomString(3); * console.log(shortStr); // 'X5k' */ export function randomString(length) { let result = ''; for (let i = 0; i < length; i++) { result += randomChar(); } return result; } /** * Generates a random string of specified length using only numeric characters (0-9). * * @param {number} length - The length of the string to generate * @returns {string} A random numeric string of the specified length * * @example * const num = randomNumber(6); * console.log(num); // '847392' * * @example * const shortNum = randomNumber(2); * console.log(shortNum); // '45' */ export function randomNumber(length) { let result = ''; for (let i = 0; i < length; i++) { result += Math.floor(Math.random() * 10).toString(); } return result; }