Find the index of the first bracket error, skipping strings
A code playground underlines the first bracket problem in the editor before running the user’s code. “Unbalanced” is not enough: the editor needs the exact character to underline. Implement findBracketError(source), which returns the index of that character, or -1 when the brackets are fine.
findBracketError(source) // => number
(), [], and {}. Every other character is ignored, except quotes (see below).source from left to right. A closing bracket must close the most recent bracket that is still open, and it must be the same kind.' or " starts a string. The string ends at the next matching quote that is not escaped. The other quote character is ordinary inside it: "it's" is one string.\ escapes the next character, whatever it is. So \" does not end a " string, and \\ is an escaped backslash.If the input ends while a bracket or a string is still open, return the smallest index among the brackets that are still open and the quote that started the unterminated string. Otherwise return -1.
source can be 100,000 characters long, with deep nesting.
findBracketError('fn(a[0], { b: 1 })'); // => -1
findBracketError('if (x]) {}'); // => 5 ']' closes '('
findBracketError('list.push(1));'); // => 12 nothing left to close
findBracketError('{ a: [1, 2 }'); // => 11 '}' closes '['
findBracketError('wrap([{'); // => 4 the earliest bracket still open
findBracketError('call(")")'); // => -1 the ')' inside the string is ignored
findBracketError('say("hi)'); // => 3 '(' at 3 and the string at 4 are open
findBracketError('x = "abc'); // => 4 unterminated string
findBracketError(''); // => -1
With escapes (shown as the raw characters of source):
log('it\'s (fine') // => -1 \' does not end the string
"\\" + ("a") // => -1 \\ is one escaped backslash, so the second " ends the string
"\" // => 0 \" is escaped, so the string never ends
a\(b) // => -1 outside a string, \ is ordinary