-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuzzy.js
72 lines (65 loc) · 1.59 KB
/
fuzzy.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
function levenshteinDistance(str1, str2) {
const len1 = str1.length;
const len2 = str2.length;
let matrix = Array(len1 + 1);
for (let i = 0; i <= len1; i++) {
matrix[i] = Array(len2 + 1);
}
for (let i = 0; i <= len1; i++) {
matrix[i][0] = i;
}
for (let j = 0; j <= len2; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
if (str1[i - 1] === str2[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j - 1] + 1
);
}
}
}
return matrix[len1][len2];
}
// Wraps an object (like ns) with a fuzzy string matcher
function FuzzyWrapper(obj) {
const handler = {
get(target, prop, receiver) {
// save a little work if it was typed correctly
if (Object.hasOwn(prop)) {
return target[prop];
}
let props = Object.keys(target), bm, bd = Infinity, bmc = 0;
for (let eprop of props) {
let d = levenshteinDistance(prop, eprop);
if (d < bd) {
bm = eprop;
bd = d;
bmc = 1;
} else if (d == bd) {
bmc++;
}
}
if (bmc > 1) {
throw `ambiguous property ${prop}`;
}
let val = target[bm];
if (typeof val == 'object') {
return FuzzyWrapper(val);
}
return val;
},
};
return new Proxy(obj, handler);
}
/** @param {NS} ns */
export async function main(ns) {
let bs = FuzzyWrapper(ns);
bs.fail();
bs.pring(bs.enms.CiN.A);
}