@@ -42,12 +42,17 @@ export default function suggestionList(
42
42
class LexicalDistance {
43
43
_input : string ;
44
44
_inputLowerCase : string ;
45
- _cells : Array < Array < number >> ;
45
+ _rows : [ Array < number > , Array < number > , Array < number > ] ;
46
46
47
47
constructor ( input : string ) {
48
48
this . _input = input ;
49
49
this . _inputLowerCase = input . toLowerCase ( ) ;
50
- this . _cells = [ ] ;
50
+
51
+ this . _rows = [
52
+ new Array ( input . length + 1 ) . fill ( 0 ) ,
53
+ new Array ( input . length + 1 ) . fill ( 0 ) ,
54
+ new Array ( input . length + 1 ) . fill ( 0 ) ,
55
+ ] ;
51
56
}
52
57
53
58
measure ( option : string ) : number {
@@ -62,39 +67,40 @@ class LexicalDistance {
62
67
return 1 ;
63
68
}
64
69
65
- const d = this . _cells ;
66
70
const a = optionLowerCase ;
67
71
const b = this . _inputLowerCase ;
68
72
const aLength = a . length ;
69
73
const bLength = b . length ;
70
74
71
- for ( let i = 0 ; i <= aLength ; i ++ ) {
72
- d [ i ] = [ i ] ;
73
- }
74
-
75
- for ( let j = 1 ; j <= bLength ; j ++ ) {
76
- d [ 0 ] [ j ] = j ;
75
+ const rows = this . _rows ;
76
+ for ( let j = 0 ; j <= bLength ; j ++ ) {
77
+ rows [ 0 ] [ j ] = j ;
77
78
}
78
79
79
80
for ( let i = 1 ; i <= aLength ; i ++ ) {
81
+ const upRow = rows [ ( i - 1 ) % 3 ] ;
82
+ const currentRow = rows [ i % 3 ] ;
83
+
84
+ currentRow [ 0 ] = i ;
80
85
for ( let j = 1 ; j <= bLength ; j ++ ) {
81
86
const cost = a [ i - 1 ] === b [ j - 1 ] ? 0 : 1 ;
82
87
83
88
let currentCell = Math . min (
84
- d [ i - 1 ] [ j ] + 1 , // delete
85
- d [ i ] [ j - 1 ] + 1 , // insert
86
- d [ i - 1 ] [ j - 1 ] + cost , // substitute
89
+ upRow [ j ] + 1 , // delete
90
+ currentRow [ j - 1 ] + 1 , // insert
91
+ upRow [ j - 1 ] + cost , // substitute
87
92
) ;
88
93
89
94
if ( i > 1 && j > 1 && a [ i - 1 ] === b [ j - 2 ] && a [ i - 2 ] === b [ j - 1 ] ) {
90
95
// transposition
91
- currentCell = Math . min ( currentCell , d [ i - 2 ] [ j - 2 ] + 1 ) ;
96
+ const doubleDiagonalCell = rows [ ( i - 2 ) % 3 ] [ j - 2 ] ;
97
+ currentCell = Math . min ( currentCell , doubleDiagonalCell + 1 ) ;
92
98
}
93
99
94
- d [ i ] [ j ] = currentCell ;
100
+ currentRow [ j ] = currentCell ;
95
101
}
96
102
}
97
103
98
- return d [ aLength ] [ bLength ] ;
104
+ return rows [ aLength % 3 ] [ bLength ] ;
99
105
}
100
106
}
0 commit comments