blob: ad79ea58eb59a09067a5be3399a3c0dd0a274c03 (
plain)
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
|
'use strict';
const { codeOnly } = require('./lexical');
const pairs = { ')': '(', ']': '[' };
function unmatchedBrackets(text) {
const code = codeOnly(text);
const stack = [];
const unmatched = [];
for (let offset = 0; offset < code.length; offset++) {
const char = code[offset];
if (char === '(' || char === '[') {
stack.push({ char, offset });
} else if (pairs[char]) {
const opening = stack.pop();
if (!opening || opening.char !== pairs[char]) {
if (opening) unmatched.push(opening.offset);
unmatched.push(offset);
}
}
}
return unmatched.concat(stack.map(opening => opening.offset)).sort((a, b) => a - b);
}
module.exports = { unmatchedBrackets };
|