Guest User

Untitled

a guest
Oct 1st, 2018
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. const LETTERS = 'qwertyuiopasdfghjklzxcvbnm';
  2. const CAPITAL_LETTERS = LETTERS.toUpperCase();
  3. const DIGITS = '1234567890';
  4. const SYMBOLS = '!@#$%^&*()-_=+[]\\{}|;\':",./<>?`';
  5.  
  6. const generatePassword = ({ length, pool }) => Array.from({ length }).reduce(
  7. (password) => password + drawElement(drawPoolEntry(pool).characters),
  8. ''
  9. );
  10. const drawElement = (array) => array[drawIndex(array)];
  11. const drawIndex = (array) => Math.floor(Math.random() * array.length);
  12. const drawPoolEntry = (pool) => {
  13. const ranges = buildPoolRanges(pool);
  14. const random = Math.random();
  15. const rangeIndex = ranges.findIndex((range) => isValueInRange(random, range));
  16. return pool[rangeIndex];
  17. };
  18. const buildPoolRanges = (pool) => {
  19. const weightSum = pool.reduce((sum, { weight }) => sum + weight, 0);
  20. const ranges = [];
  21. let rangeStart = 0;
  22. pool.forEach(({ weight }) => {
  23. const rangeEnd = rangeStart + weight / weightSum;
  24. ranges.push([ rangeStart, rangeEnd ]);
  25. rangeStart = rangeEnd;
  26. });
  27. return ranges;
  28. };
  29. const isValueInRange = (value, [ rangeStart, rangeEnd ]) => rangeStart <= value && value < rangeEnd;
  30.  
  31. console.clear();
  32. console.log(generatePassword({
  33. length: 16,
  34. pool: [
  35. {
  36. characters: LETTERS,
  37. weight: 1
  38. },
  39. {
  40. characters: CAPITAL_LETTERS,
  41. weight: 1
  42. },
  43. {
  44. characters: DIGITS,
  45. weight: 1
  46. },
  47. {
  48. characters: SYMBOLS,
  49. weight: 1
  50. }
  51. ]
  52. }));
Add Comment
Please, Sign In to add comment