Skip to content

Commit 122b741

Browse files
committed
suggestionList: use only 3 rows instead of full matrix
1 parent bd4deb0 commit 122b741

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

src/jsutils/suggestionList.js

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,17 @@ export default function suggestionList(
4242
class LexicalDistance {
4343
_input: string;
4444
_inputLowerCase: string;
45-
_cells: Array<Array<number>>;
45+
_rows: [Array<number>, Array<number>, Array<number>];
4646

4747
constructor(input: string) {
4848
this._input = input;
4949
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+
];
5156
}
5257

5358
measure(option: string): number {
@@ -62,39 +67,40 @@ class LexicalDistance {
6267
return 1;
6368
}
6469

65-
const d = this._cells;
6670
const a = optionLowerCase;
6771
const b = this._inputLowerCase;
6872
const aLength = a.length;
6973
const bLength = b.length;
7074

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;
7778
}
7879

7980
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;
8085
for (let j = 1; j <= bLength; j++) {
8186
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
8287

8388
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
8792
);
8893

8994
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
9095
// 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);
9298
}
9399

94-
d[i][j] = currentCell;
100+
currentRow[j] = currentCell;
95101
}
96102
}
97103

98-
return d[aLength][bLength];
104+
return rows[aLength % 3][bLength];
99105
}
100106
}

0 commit comments

Comments
 (0)