Skip to content

Instantly share code, notes, and snippets.

@mohitxskull
Created January 5, 2023 06:33
Show Gist options
  • Select an option

  • Save mohitxskull/fd8ade85705c650ae6dfc2b683d5a907 to your computer and use it in GitHub Desktop.

Select an option

Save mohitxskull/fd8ade85705c650ae6dfc2b683d5a907 to your computer and use it in GitHub Desktop.

Revisions

  1. mohitxskull created this gist Jan 5, 2023.
    87 changes: 87 additions & 0 deletions passGen.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,87 @@
    const passwordGen = (
    length = 8,
    {
    includeLowercase: inLc = true,
    includeUppercase: inUc = true,
    includeNumbers: inN = true,
    includeSymbols: inS = true,
    numberOfSymbols: nOfS = 1,
    numberOfNumbers: nOfN = 1,
    numberOfUppercase: nOfUc = 1,
    numberOfLowercase: nOfLc = 1,
    numberOfPassword: nOfPass = 1,
    }
    ) => {
    const password = [];
    const lowercase = 'abcdefghijklmnopqrstuvwxyz';
    const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const numbers = '0123456789';
    const symbols = '!@#$%^&*()_+~`|}{[]:;?><,./-=';

    const passwordPool = inLc
    ? lowercase
    : inN
    ? numbers
    : inS
    ? symbols
    : inUc
    ? uppercase
    : '';

    const internalPasswordGen = () => {
    let sinPass = '';
    // Add numbers if includeNumbers is true
    if (inN) {
    for (let i = 0; i < nOfN; i++) {
    sinPass += numbers[Math.floor(Math.random() * 10)];
    }
    }
    // Add symbols if includeSymbols is true
    if (inS) {
    for (let i = 0; i < nOfS; i++) {
    sinPass += symbols[Math.floor(Math.random() * 30)];
    }
    }
    // Add lowercase if includeLowercase is true
    if (inLc) {
    for (let i = 0; i < nOfLc; i++) {
    sinPass += lowercase[Math.floor(Math.random() * 26)];
    }
    }
    // Add uppercase if includeUppercase is true
    if (inUc) {
    for (let i = 0; i < nOfUc; i++) {
    sinPass += uppercase[Math.floor(Math.random() * 26)];
    }
    }
    // remove characters if the password is longer than the length
    // add characters if the password is shorter than the length
    if (sinPass.length > length) {
    sinPass = sinPass.slice(0, length);
    } else if (sinPass.length < length) {
    for (let i = 0; i < length - sinPass.length; i++) {
    sinPass +=
    passwordPool[Math.floor(Math.random() * passwordPool.length)];
    }
    }
    // Shuffle the password
    sinPass = sinPass
    .split('')
    .sort(() => Math.random() - 0.5)
    .join('');

    return sinPass;
    };
    for (let i = 0; i < nOfPass; i++) {
    password.push(internalPasswordGen());
    }
    return password;
    };

    // passwordGen(16, {
    // numberOfNumbers: 4,
    // numberOfSymbols: 2,
    // numberOfPassword: 5,
    // });

    // Output: [ '{v5n0huD6y.9', '9m3Zw;kb71(a', '1,0o3Xc<ss9x', '3mq|0[Wqiq92', 'fw16[O-hr42q' ];