Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const LETTERS = 'qwertyuiopasdfghjklzxcvbnm';
- const CAPITAL_LETTERS = LETTERS.toUpperCase();
- const DIGITS = '1234567890';
- const SYMBOLS = '!@#$%^&*()-_=+[]\\{}|;\':",./<>?`';
- const generatePassword = ({ length, pool }) => Array.from({ length }).reduce(
- (password) => password + drawElement(drawPoolEntry(pool).characters),
- ''
- );
- const drawElement = (array) => array[drawIndex(array)];
- const drawIndex = (array) => Math.floor(Math.random() * array.length);
- const drawPoolEntry = (pool) => {
- const ranges = buildPoolRanges(pool);
- const random = Math.random();
- const rangeIndex = ranges.findIndex((range) => isValueInRange(random, range));
- return pool[rangeIndex];
- };
- const buildPoolRanges = (pool) => {
- const weightSum = pool.reduce((sum, { weight }) => sum + weight, 0);
- const ranges = [];
- let rangeStart = 0;
- pool.forEach(({ weight }) => {
- const rangeEnd = rangeStart + weight / weightSum;
- ranges.push([ rangeStart, rangeEnd ]);
- rangeStart = rangeEnd;
- });
- return ranges;
- };
- const isValueInRange = (value, [ rangeStart, rangeEnd ]) => rangeStart <= value && value < rangeEnd;
- console.clear();
- console.log(generatePassword({
- length: 16,
- pool: [
- {
- characters: LETTERS,
- weight: 1
- },
- {
- characters: CAPITAL_LETTERS,
- weight: 1
- },
- {
- characters: DIGITS,
- weight: 1
- },
- {
- characters: SYMBOLS,
- weight: 1
- }
- ]
- }));
Add Comment
Please, Sign In to add comment