Created
February 14, 2023 22:06
-
-
Save mjmeilahn/edee3b18dece10acc4bb8cba572f17e3 to your computer and use it in GitHub Desktop.
JS: Valid String Closures.
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
/* | |
Return TRUE or FALSE whether the string has valid closures. | |
A valid closure can be: () or ({}) or []({}). | |
An invalid closure interrupts open/close characters. | |
Each opener character must have a closer character. | |
Each closer character must have an opener character. | |
*/ | |
const patterns = { | |
'{': '}', | |
'[': ']', | |
'(': ')', | |
} | |
const validPattern = str => { | |
let invalid = false | |
const arr = str.split('') | |
const openers = Object.keys(patterns) | |
const closers = Object.values(patterns) | |
const o = [] | |
const c = [] | |
arr.map((char, i) => { | |
if (openers.includes(char)) o.push(char) | |
if (closers.includes(char)) c.push(char) | |
const prev = arr[i - 1] | |
const next = arr[i + 1] | |
const openIndex = openers.findIndex(i => i === prev) | |
const closeIndex = closers.findIndex(i => i === next) | |
if (openers.includes(prev) && closers.includes(next) && openIndex === closeIndex) { | |
invalid = true | |
} | |
}) | |
if (invalid) return false | |
return (o.length !== c.length) ? false : true | |
} | |
console.log(validPattern('{([])}')) // TRUE | |
console.log(validPattern('{}[]()')) // TRUE | |
console.log(validPattern('{()}[]')) // TRUE | |
console.log(validPattern('[)]')) // FALSE | |
console.log(validPattern('{[]}(')) // FALSE | |
console.log(validPattern('}{}')) // FALSE | |
console.log(validPattern('{[]')) // FALSE | |
console.log(validPattern('{[(])]}')) // FALSE | |
console.log(validPattern('[(])')) // FALSE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment