UNPKG

1.64 kBJavaScriptView Raw
1function ensureValidUseOfParenthesesOrBrackets(pattern) {
2 var counts = {
3 '[': 0,
4 ']': 0,
5 '(': 0,
6 ')': 0
7 };
8 for (var i = 0; i < pattern.length; i += 1) {
9 var c = pattern.charAt(i);
10 if (c in counts) {
11 counts[c] += 1;
12 }
13 if (c === ']' && counts['['] >= counts[']']) {
14 if (counts['['] === counts[']'] + 1) {
15 throw new Error(
16 ("Assertion patterns must not contain flags with brackets: '" + pattern + "'")
17 );
18 }
19
20 if (counts['('] !== counts[')']) {
21 throw new Error(
22 ("Assertion patterns must not contain flags with parentheses: '" + pattern + "'")
23 );
24 }
25
26 if (pattern.charAt(i - 1) === '[') {
27 throw new Error(
28 ("Assertion patterns must not contain empty flags: '" + pattern + "'")
29 );
30 }
31 } else if (c === ')' && counts['('] >= counts[')']) {
32 if (counts['('] === counts[')'] + 1) {
33 throw new Error(
34 ("Assertion patterns must not contain alternations with parentheses: '" + pattern + "'")
35 );
36 }
37
38 if (counts['['] !== counts[']']) {
39 throw new Error(
40 ("Assertion patterns must not contain alternations with brackets: '" + pattern + "'")
41 );
42 }
43 }
44 }
45
46 if (counts['['] !== counts[']']) {
47 throw new Error(
48 ("Assertion patterns must not contain unbalanced brackets: '" + pattern + "'")
49 );
50 }
51
52 if (counts['('] !== counts[')']) {
53 throw new Error(
54 ("Assertion patterns must not contain unbalanced parentheses: '" + pattern + "'")
55 );
56 }
57}
58
59module.exports = ensureValidUseOfParenthesesOrBrackets;