Skip to content

Instantly share code, notes, and snippets.

@ogabrielguerra
Created February 17, 2024 20:37
Show Gist options
  • Save ogabrielguerra/9adb108145dfb8bb864ac081667cda29 to your computer and use it in GitHub Desktop.
Save ogabrielguerra/9adb108145dfb8bb864ac081667cda29 to your computer and use it in GitHub Desktop.
Checks if a given string has the expected closing char.
const testString = (s)=>{
console.log('Evaluating string ', s)
let opening = ['(', '[', '{']
let closing = [')', ']', '}']
const findIndex = (list, char) =>{
for (let i in list)
if(list[i]===char) return i;
}
//s lenght must be even
if(s.length %2 !== 0) {
console.log(`String ${s} length is odd.`);
return false
}
for (let i = 0; i < s.length; i+=2) {
let currentChar = s.charAt(i)
let nextChar = s.charAt(i+1)
let currentIndex = findIndex(opening, currentChar);
if (nextChar !== closing[currentIndex])
return false
}
return true;
}
let s1 = "()";
console.log(testString(s1))
let s2 = "()[]{}"
console.log(testString(s2))
let s3 = "(]"
console.log(testString(s3))
let s4 = "()[]{}("
console.log(testString(s4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment