-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
index.js
75 lines (65 loc) · 1.37 KB
/
index.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
/**
* @param {string | RegExp} a
* @param {string | RegExp} b
* @param {string} str
*/
export default function balanced (a, b, str) {
if (a instanceof RegExp) a = maybeMatch(a, str)
if (b instanceof RegExp) b = maybeMatch(b, str)
const r = range(a, b, str)
return (
r && {
start: r[0],
end: r[1],
pre: str.slice(0, r[0]),
body: str.slice(r[0] + a.length, r[1]),
post: str.slice(r[1] + b.length)
}
)
}
/**
* @param {RegExp} reg
* @param {string} str
*/
function maybeMatch (reg, str) {
const m = str.match(reg)
return m ? m[0] : null
}
/**
* @param {string} a
* @param {string} b
* @param {string} str
*/
export function range (a, b, str) {
let begs, beg, left, right, result
let ai = str.indexOf(a)
let bi = str.indexOf(b, ai + 1)
let i = ai
if (ai >= 0 && bi > 0) {
if (a === b) {
return [ai, bi]
}
begs = []
left = str.length
while (i >= 0 && !result) {
if (i === ai) {
begs.push(i)
ai = str.indexOf(a, i + 1)
} else if (begs.length === 1) {
result = [begs.pop(), bi]
} else {
beg = begs.pop()
if (beg < left) {
left = beg
right = bi
}
bi = str.indexOf(b, i + 1)
}
i = ai < bi && ai >= 0 ? ai : bi
}
if (begs.length) {
result = [left, right]
}
}
return result
}