-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary.js
93 lines (77 loc) · 1.68 KB
/
library.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const { exec } = require("child_process");
function openBrowser(url) {
switch (process.platform) {
case "darwin":
exec(`open ${url}`);
break;
case "win32":
exec(`start ${url}`);
break;
default:
exec(`xdg-open ${url}`);
break;
}
}
function checkDistance(a, b) {
if (a.startsWith(b)) {
return 0;
}
const matrix = [];
let i, j;
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
for (i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j] + 1
);
}
}
}
return matrix[b.length][a.length];
}
class NameMatcher {
constructor(alias, data) {
this.alias = alias;
this.data = data;
}
getAlias() {
return this.alias;
}
getData() {
return this.data;
}
static getBestMatch(query, candidatesList) {
let closestMatch = null;
let smallestDistance = Infinity;
for (const candidate of candidatesList) {
const distance = checkDistance(
query,
candidate.alias || candidate.data
);
if (distance < smallestDistance) {
smallestDistance = distance;
closestMatch = candidate;
}
}
if (!closestMatch) {
throw new Error("No matching names found.");
}
return closestMatch;
}
}
module.exports = {
openBrowser,
NameMatcher
};