Created
October 31, 2021 19:02
-
-
Save cagataycali/6bf1c467d4f14e58db096f9a195e56b3 to your computer and use it in GitHub Desktop.
[JavaScript] Brackets validator
This file contains hidden or 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
| const assert = require('assert'); | |
| // '(', '{', '[' are called "openers." | |
| // ')', '}', ']' are called "closers." | |
| function validateBrackets(input) { | |
| const brackets = { | |
| openings: { | |
| '{': '}', | |
| '(': ')', | |
| '[': ']' | |
| }, | |
| closing: { | |
| '}': '{', | |
| ')': '(', | |
| ']': '[' | |
| } | |
| } | |
| const stack = []; | |
| for (const char of input) { | |
| // Opening | |
| if (brackets.openings[char]) { | |
| stack.push(char) | |
| } else if (brackets.closing[char]) { | |
| // Stack is empty | |
| if (stack.length === 0) return false; | |
| if (stack[stack.length - 1] === brackets.closing[char]) { | |
| stack.pop() | |
| } else { | |
| return false; | |
| } | |
| } | |
| } | |
| return stack.length === 0 | |
| } | |
| assert.deepStrictEqual(validateBrackets('{[]}'), true) | |
| assert.deepStrictEqual(validateBrackets('{[}'), false) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment