-
Notifications
You must be signed in to change notification settings - Fork 754
/
utils.ts
78 lines (64 loc) · 2.04 KB
/
utils.ts
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
export function each(incoming) {
return [].slice.call(incoming || []);
}
export const splitUrl = function(url) {
let hash, index, params;
if ((index = url.indexOf("#")) >= 0) {
hash = url.slice(index);
url = url.slice(0, index);
} else {
hash = "";
}
if ((index = url.indexOf("?")) >= 0) {
params = url.slice(index);
url = url.slice(0, index);
} else {
params = "";
}
return { url, params, hash };
};
export const pathFromUrl = function(url) {
let path;
({ url } = splitUrl(url));
if (url.indexOf("file://") === 0) {
path = url.replace(new RegExp(`^file://(localhost)?`), "");
} else {
// http : // hostname :8080 /
path = url.replace(new RegExp(`^([^:]+:)?//([^:/]+)(:\\d*)?/`), "/");
}
// decodeURI has special handling of stuff like semicolons, so use decodeURIComponent
return decodeURIComponent(path);
};
export const pickBestMatch = function(path, objects, pathFunc): any {
let score;
let bestMatch = { score: 0, object: null };
objects.forEach(object => {
score = numberOfMatchingSegments(path, pathFunc(object));
if (score > bestMatch.score) {
bestMatch = { object, score };
}
});
if (bestMatch.score > 0) {
return bestMatch;
} else {
return null;
}
};
export const numberOfMatchingSegments = function(path1, path2) {
// get rid of leading slashes and normalize to lower case
path1 = path1.replace(/^\/+/, "").toLowerCase();
path2 = path2.replace(/^\/+/, "").toLowerCase();
if (path1 === path2) {
return 10000;
}
const comps1 = path1.split("/").reverse();
const comps2 = path2.split("/").reverse();
const len = Math.min(comps1.length, comps2.length);
let eqCount = 0;
while (eqCount < len && comps1[eqCount] === comps2[eqCount]) {
++eqCount;
}
return eqCount;
};
export const pathsMatch = (path1, path2) =>
numberOfMatchingSegments(path1, path2) > 0;