Created
January 3, 2024 19:27
-
-
Save ramonrails/e9416059376845145e90f6ca2be002ea to your computer and use it in GitHub Desktop.
Matching brackets (simple version)
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
// matching the brackets | |
// * one type of brackets only | |
// * opening must appear before closing bracket | |
// * pre or post padding characters should not affect the result | |
// * any other characters in0between anywhere should not affect the result | |
// | |
const balanced = (arg) => { | |
// | |
// `for char of result` should also work here | |
// | |
const result = arg.split('').reduce((final, char) => { | |
// | |
// return-early or fail-fast pattern | |
// | |
if(final < 0) return final // when we have -1, we have failed already, save time & resources, return | |
if(char === '(') return ++final // increment the counter when opening bracket found | |
if(char === ')') return --final // decrement, when closing bracket count | |
return final // no change, just return the value we currently have | |
}, 0) // start from ZERO count | |
return result === 0 ? 'Balanced' : 'Nah!' | |
} | |
// test cases | |
// | |
console.log(balanced("")) | |
console.log(balanced("()")) | |
console.log(balanced("(())")) | |
console.log(balanced(">> ( something() 876545678765$%^&^%$ in between( and multiple() levels too))")) | |
console.log(balanced("())")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment