Last active
May 4, 2018 09:23
-
-
Save jenyayel/456022b65b6fae196874 to your computer and use it in GitHub Desktop.
Implement function check (text) which checks whether brackets within text are correctly nested. You need to consider brackets of three kinds: (), [], {}.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var expect = require('expect') | |
var _matches = { | |
'{': { invert: '}', isOpening: true }, | |
'}': { invert: '{', isOpening: false }, | |
'(': { invert: ')', isOpening: true }, | |
')': { invert: '(', isOpening: false }, | |
'[': { invert: ']', isOpening: true }, | |
']': { invert: '[', isOpening: false } | |
}; | |
function check (input) { | |
var bracketsStack = []; | |
for (var index = 0; index < input.length; index++) { | |
var char = input[index]; | |
if(!_matches[char]) continue; // not a bracket | |
if (!_matches[char].isOpening) { | |
if(bracketsStack.length == 0 || bracketsStack[bracketsStack.length - 1] != _matches[char].invert) | |
return false; // no opening bracket for a currently closing found | |
else | |
bracketsStack.pop(); | |
} | |
else if (_matches[char].isOpening) | |
bracketsStack.push(char); | |
} | |
return bracketsStack.length == 0; | |
} | |
expect(check("a(b)")).toBe(true); | |
expect(check("[{}]")).toBe(true); | |
expect(check("[(]")).toBe(false); | |
expect(check("[(])")).toBe(false); | |
expect(check("[}")).toBe(false); | |
expect(check("}{")).toBe(false); | |
expect(check("z([{}-()]{a})")).toBe(true); | |
expect(check("")).toBe(true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment