Skip to content

Instantly share code, notes, and snippets.

@DigitalKrony
Created March 1, 2019 00:47
Show Gist options
  • Save DigitalKrony/c78d85baab2cf601db39a7fdb3e0b57e to your computer and use it in GitHub Desktop.
Save DigitalKrony/c78d85baab2cf601db39a7fdb3e0b57e to your computer and use it in GitHub Desktop.
A simple function that generates an alpha/numeric key
const generateKey = (len=5, options) => {
let generated_key = '';
let config = {
keyCharacters: 'aAbBcCdDeEgFhGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789',
...options
};
if (typeof len === 'object') {
for (let i = 0; i < len.length; i++) {
generated_key += generateKey(len[i]);
if (i !== len.length-1)
generated_key+='-';
}
} else if (typeof len === 'number') {
let value = '';
for (let i = 0; i < len; i++) {
value += config.keyCharacters[Math.floor(Math.random() * config.keyCharacters.length)];
}
return value;
}
return generated_key;
}
// generateKey(24) // generates a 24 character Key ( NhxZiwpu7BKgClX1r8ciGLD2 )
// generateKey([8,4,4,8]) // generates an 8x4x4x8 Key ( tVUa64SG-oRmc-EqnG-2Z6e4mTO )
// generateKey(6,{keyCharacters:'0123456789ABCDEF'}) // Generates a HEX color ( 542A74 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment