Last active
May 15, 2020 07:32
-
-
Save rxluz/db62d70bdd424d595090bd0804fd969c to your computer and use it in GitHub Desktop.
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 tests = { | |
valid: '{[(())]}', | |
valid2: '{}', | |
valid3: '()', | |
valid4: '[]', | |
valid5: '{[]}', | |
valid6: '{[()]}', | |
valid7: '', | |
valid8: '[]{}[][]()()', | |
invalid0: '[{}]', | |
invalid1: ']})', | |
invalid2: '[{]}', | |
invalid3: '{[(', | |
invalid4: '((({{{}}})))', | |
invalid5: '[{()}]', | |
} | |
const BRACKETS_LIST = { | |
'{': '}', | |
'[': ']', | |
'(': ')', | |
} | |
const OPENING_BRACKETS_LIST = Object.keys(BRACKETS_LIST).join('') | |
const isOpeningBrackets = (item) => OPENING_BRACKETS_LIST.includes(item) | |
const isCorrectOrder = (first, second) => { | |
if (first === false) { | |
return true | |
} | |
const isValidItems = | |
OPENING_BRACKETS_LIST.includes(first) && | |
OPENING_BRACKETS_LIST.includes(second) | |
const isValidOrder = | |
OPENING_BRACKETS_LIST.indexOf(first) <= | |
OPENING_BRACKETS_LIST.indexOf(second) | |
return isValidItems && isValidOrder | |
} | |
const isCorrectClosingItem = (opening, closing) => | |
BRACKETS_LIST[opening] === closing | |
function isValidBrackets(input) { | |
const stack = [] | |
let isValid = true | |
for (let cursor = 0; isValid && cursor < input.length; cursor++) { | |
const currentItem = input[cursor] | |
const topItemInStack = stack[stack.length - 1] || false | |
if (isOpeningBrackets(currentItem)) { | |
if (isCorrectOrder(topItemInStack, currentItem)) { | |
stack.push(currentItem) | |
} else { | |
isValid = false | |
} | |
} else if (isCorrectClosingItem(topItemInStack, currentItem)) { | |
stack.length = stack.length - 1 | |
} else { | |
isValid = false | |
} | |
} | |
if (stack.length > 0) { | |
isValid = false | |
} | |
return isValid | |
} | |
Object.keys(tests).map((key) => | |
console.log( | |
`Testing ${key} - ${tests[key]} ::: ${isValidBrackets(tests[key])}` | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment