@@ -13,12 +13,13 @@ export default function suggestionList(
13
13
14
14
const inputThreshold = input . length / 2 ;
15
15
for ( const option of options ) {
16
- const distance = lexicalDistance . measure ( option ) ;
17
16
const threshold = Math . max ( inputThreshold , option . length / 2 , 1 ) ;
18
- if ( distance <= threshold ) {
17
+ const distance = lexicalDistance . measure ( option , threshold ) ;
18
+ if ( distance !== undefined ) {
19
19
optionsByDistance [ option ] = distance ;
20
20
}
21
21
}
22
+
22
23
return Object . keys ( optionsByDistance ) . sort ( ( a , b ) => {
23
24
const distanceDiff = optionsByDistance [ a ] - optionsByDistance [ b ] ;
24
25
return distanceDiff !== 0 ? distanceDiff : a . localeCompare ( b ) ;
@@ -55,7 +56,7 @@ class LexicalDistance {
55
56
] ;
56
57
}
57
58
58
- measure ( option : string ) : number {
59
+ measure ( option : string , threshold : number ) : number | void {
59
60
if ( this . _input === option ) {
60
61
return 0 ;
61
62
}
@@ -69,9 +70,14 @@ class LexicalDistance {
69
70
70
71
const a = optionLowerCase ;
71
72
const b = this . _inputLowerCase ;
73
+
72
74
const aLength = a . length ;
73
75
const bLength = b . length ;
74
76
77
+ if ( Math . abs ( aLength - bLength ) > threshold ) {
78
+ return undefined ;
79
+ }
80
+
75
81
const rows = this . _rows ;
76
82
for ( let j = 0 ; j <= bLength ; j ++ ) {
77
83
rows [ 0 ] [ j ] = j ;
@@ -81,7 +87,7 @@ class LexicalDistance {
81
87
const upRow = rows [ ( i - 1 ) % 3 ] ;
82
88
const currentRow = rows [ i % 3 ] ;
83
89
84
- currentRow [ 0 ] = i ;
90
+ let smallestCell = ( currentRow [ 0 ] = i ) ;
85
91
for ( let j = 1 ; j <= bLength ; j ++ ) {
86
92
const cost = a [ i - 1 ] === b [ j - 1 ] ? 0 : 1 ;
87
93
@@ -97,10 +103,20 @@ class LexicalDistance {
97
103
currentCell = Math . min ( currentCell , doubleDiagonalCell + 1 ) ;
98
104
}
99
105
106
+ if ( currentCell < smallestCell ) {
107
+ smallestCell = currentCell ;
108
+ }
109
+
100
110
currentRow [ j ] = currentCell ;
101
111
}
112
+
113
+ // Early exit, since distance can't go smaller than smallest element of the previous row.
114
+ if ( smallestCell > threshold ) {
115
+ return undefined ;
116
+ }
102
117
}
103
118
104
- return rows [ aLength % 3 ] [ bLength ] ;
119
+ const distance = rows [ aLength % 3 ] [ bLength ] ;
120
+ return distance <= threshold ? distance : undefined ;
105
121
}
106
122
}
0 commit comments