Created
August 31, 2018 14:23
-
-
Save dearenot/f860b90b602c7ae514566873b029c5b5 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 round = ["(", ")"]; | |
| const square = ["[", "]"]; | |
| const curly = ["{", "}"]; | |
| const left = [round[0], square[0], curly[0]]; | |
| const right = [round[1], square[1], curly[1]]; | |
| const isLeft = (char) => { | |
| return left.includes(char) | |
| } | |
| const isRight = (char) => { | |
| return right.includes(char) | |
| } | |
| const isSameType = (char1, char2) => { | |
| return round.includes(char1) && round.includes(char2) || | |
| square.includes(char1) && square.includes(char2) || | |
| curly.includes(char1) && curly.includes(char2) | |
| } | |
| const checkBrackets = (str) => { | |
| const arr = Array.from(str); | |
| let toReturn = false; | |
| arr.forEach((char, index) => { | |
| const prev = (str[index - 1]) ? str[index - 1] : null; | |
| //console.log(prev, char, isLeft(prev), isRight(char), isSameType(char, prev)) | |
| if (isLeft(prev) && isRight(char) && !isSameType(prev, char)) { | |
| //console.log("!!!!!!!!!!!!") | |
| toReturn = true; | |
| return false; | |
| } | |
| }); | |
| if (toReturn) return false; | |
| const leftCount = arr.filter((char) => isLeft(char)).length; | |
| const rightCount = arr.filter((char) => isRight(char)).length; | |
| return (leftCount === rightCount); | |
| } | |
| console.clear() | |
| console.log(isLeft("("), isLeft("{"), isLeft("["), isLeft(")")) | |
| const true_1 = "{[()]}"; | |
| const true_2 = "()[{}]()"; | |
| const true_3 = "{}[]()"; | |
| const false_1 = "[){}(]" | |
| const false_2 = "())" | |
| const false_3 = "[{)]" | |
| /* console.log(isSameType("(", ")")); | |
| console.log(isSameType("(", "(")); | |
| console.log(isSameType("}", ")")); */ | |
| console.log(checkBrackets(true_1)) | |
| console.log(checkBrackets(true_2)) | |
| console.log(checkBrackets(true_3)) | |
| console.log(checkBrackets(false_1)) | |
| console.log(checkBrackets(false_2)) | |
| console.log(checkBrackets(false_3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment