getSuggestion.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports["default"] = getSuggestion;
  7. var _damerauLevenshtein = _interopRequireDefault(require("damerau-levenshtein"));
  8. // Minimum edit distance to be considered a good suggestion.
  9. var THRESHOLD = 2;
  10. /**
  11. * Returns an array of suggestions given a word and a dictionary and limit of suggestions
  12. * to return.
  13. */
  14. function getSuggestion(word) {
  15. var dictionary = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  16. var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
  17. var distances = dictionary.reduce(function (suggestions, dictionaryWord) {
  18. var distance = (0, _damerauLevenshtein["default"])(word.toUpperCase(), dictionaryWord.toUpperCase());
  19. var steps = distance.steps;
  20. suggestions[dictionaryWord] = steps; // eslint-disable-line
  21. return suggestions;
  22. }, {});
  23. return Object.keys(distances).filter(function (suggestion) {
  24. return distances[suggestion] <= THRESHOLD;
  25. }).sort(function (a, b) {
  26. return distances[a] - distances[b];
  27. }) // Sort by distance
  28. .slice(0, limit);
  29. }