Skip to content

Instantly share code, notes, and snippets.

@maoosi
Last active September 28, 2018 05:07
Show Gist options
  • Save maoosi/e68446a7917072135a219a4c6f18fbac to your computer and use it in GitHub Desktop.
Save maoosi/e68446a7917072135a219a4c6f18fbac to your computer and use it in GitHub Desktop.
Function to generate alpha-numeric strings. First parameter is the length, second parameters is the number of numeric characters.
const getUniq = (digits, nbTotalNumerics) => {
let numerics = '0123456789';
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let nbNumerics = 0;
let uniqCode = '';
for (let i = digits; i > 0; --i) {
let forceNumeric = (i <= nbTotalNumerics && nbNumerics < nbTotalNumerics);
if ((forceNumeric || (Math.floor(Math.random() * 2) + 0) === 0) && nbNumerics < nbTotalNumerics) {
uniqCode += '' + numerics[ Math.floor(Math.random() * numerics.length) ];
nbNumerics++;
} else {
uniqCode += '' + alphabet[ Math.floor(Math.random() * alphabet.length) ];
}
}
return uniqCode;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment