randomPassword()

๐Ÿ’พ replit

// โญ๏ธ ้ ่จญๅฏ†็ขผ้•ทๅบฆ๏ผš32
function randomPassword(length = 32, {
    digit      = true,      // ่ฆๆœ‰ๆ•ธๅญ—
    lowercase  = true,      // ่ฆๆœ‰ๅฐๅฏซ
    uppercase  = true,      // ่ฆๆœ‰ๅคงๅฏซ
    underscore = true,      // ๅฏไปฅๆœ‰ "_"
    symbol     = true,      // ็‰นๆฎŠ็ฌฆ่™Ÿ
}={}){

    // 1. ๅญ—้›†
    let digits   = String.fromCharCodesBetween(48, 57);    // '0...9'
    let letters  = String.fromCharCodesBetween(97, 122);  // 'a...z'
    let capitals = String.fromCharCodesBetween(65, 90);   // 'A...Z'
    let symbols  = "!@#$%^&*";
    let underscores = "_";

    // 2. ๆบ–ๅ‚™็ต„ๅˆๅฏ†็ขผ
    let pwd = '';                       // ๅฏ†็ขผ
    let candidates = '';                // ๅฏ†็ขผๅ€™้ธๅญ—

    // 3. ๅพžๅฟ…็”จ็š„ๅญ—้›†ไธญ้ธๅญ—
    [
        [digit, digits],                // ๆ•ธๅญ—
        [lowercase, letters],           // ๅฐๅฏซ
        [uppercase, capitals],          // ๅคงๅฏซ
        [underscore, underscores],      // ๅบ•็ทš "_"
        [symbol, symbols],              // ็‰นๆฎŠ็ฌฆ่™Ÿ

    ].forEach(([include, chars]) => {
        if(include){                    // ๅฆ‚ๆžœ่ฆๅŠ ๅ…ฅ 
            pwd += chars.random();      // ๅ…ˆๅŠ ๅ…ฅไธ€ๅ€‹ๅญ—ๅ…ƒ
            candidates += chars;        // ๆ•ด็ต„ๅญ—้›†ๅŠ ๅ…ฅๅ€™้ธๅญ—
        }
    });

    // 4. ๅฆ‚ๆžœๅฏ†็ขผ้•ทๅบฆไธ่ถณ๏ผŒๅฐฑ็นผ็บŒ้ธๅญ—
    let k = pwd.length;                 // ็›ฎๅ‰ๅฏ†็ขผ้•ทๅบฆ
    let n = candidates.length;          // ้ธ็”จๅญ—็ธฝ้•ทๅบฆ

    while(k < length){
        pwd += candidates.random();
        k += 1;
    }

    return pwd.shuffle();
}

Last updated

Was this helpful?