UNPKG

2.34 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = suggestionList;
7
8/**
9 * Given an invalid input string and a list of valid options, returns a filtered
10 * list of valid options sorted based on their similarity with the input.
11 */
12function suggestionList(input, options) {
13 var optionsByDistance = Object.create(null);
14 var inputThreshold = input.length / 2;
15
16 for (var _i2 = 0; _i2 < options.length; _i2++) {
17 var option = options[_i2];
18 var distance = lexicalDistance(input, option);
19 var threshold = Math.max(inputThreshold, option.length / 2, 1);
20
21 if (distance <= threshold) {
22 optionsByDistance[option] = distance;
23 }
24 }
25
26 return Object.keys(optionsByDistance).sort(function (a, b) {
27 return optionsByDistance[a] - optionsByDistance[b];
28 });
29}
30/**
31 * Computes the lexical distance between strings A and B.
32 *
33 * The "distance" between two strings is given by counting the minimum number
34 * of edits needed to transform string A into string B. An edit can be an
35 * insertion, deletion, or substitution of a single character, or a swap of two
36 * adjacent characters.
37 *
38 * Includes a custom alteration from Damerau-Levenshtein to treat case changes
39 * as a single edit which helps identify mis-cased values with an edit distance
40 * of 1.
41 *
42 * This distance can be useful for detecting typos in input or sorting
43 *
44 * @param {string} a
45 * @param {string} b
46 * @return {int} distance in number of edits
47 */
48
49
50function lexicalDistance(aStr, bStr) {
51 if (aStr === bStr) {
52 return 0;
53 }
54
55 var d = [];
56 var a = aStr.toLowerCase();
57 var b = bStr.toLowerCase();
58 var aLength = a.length;
59 var bLength = b.length; // Any case change counts as a single edit
60
61 if (a === b) {
62 return 1;
63 }
64
65 for (var i = 0; i <= aLength; i++) {
66 d[i] = [i];
67 }
68
69 for (var j = 1; j <= bLength; j++) {
70 d[0][j] = j;
71 }
72
73 for (var _i3 = 1; _i3 <= aLength; _i3++) {
74 for (var _j = 1; _j <= bLength; _j++) {
75 var cost = a[_i3 - 1] === b[_j - 1] ? 0 : 1;
76 d[_i3][_j] = Math.min(d[_i3 - 1][_j] + 1, d[_i3][_j - 1] + 1, d[_i3 - 1][_j - 1] + cost);
77
78 if (_i3 > 1 && _j > 1 && a[_i3 - 1] === b[_j - 2] && a[_i3 - 2] === b[_j - 1]) {
79 d[_i3][_j] = Math.min(d[_i3][_j], d[_i3 - 2][_j - 2] + cost);
80 }
81 }
82 }
83
84 return d[aLength][bLength];
85}