levenshtein.js 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. var fastestLevenshtein = require('fastest-levenshtein');
  3. const getUsedThreshold = (password, entry, threshold) => {
  4. const isPasswordToShort = password.length <= entry.length;
  5. const isThresholdLongerThanPassword = password.length <= threshold;
  6. const shouldUsePasswordLength = isPasswordToShort || isThresholdLongerThanPassword;
  7. // if password is too small use the password length divided by 4 while the threshold needs to be at least 1
  8. return shouldUsePasswordLength ? Math.ceil(password.length / 4) : threshold;
  9. };
  10. const findLevenshteinDistance = (password, rankedDictionary, threshold) => {
  11. let foundDistance = 0;
  12. const found = Object.keys(rankedDictionary).find(entry => {
  13. const usedThreshold = getUsedThreshold(password, entry, threshold);
  14. const foundEntryDistance = fastestLevenshtein.distance(password, entry);
  15. const isInThreshold = foundEntryDistance <= usedThreshold;
  16. if (isInThreshold) {
  17. foundDistance = foundEntryDistance;
  18. }
  19. return isInThreshold;
  20. });
  21. if (found) {
  22. return {
  23. levenshteinDistance: foundDistance,
  24. levenshteinDistanceEntry: found
  25. };
  26. }
  27. return {};
  28. };
  29. module.exports = findLevenshteinDistance;
  30. //# sourceMappingURL=levenshtein.js.map