Skip to content

Instantly share code, notes, and snippets.

@DouglasdeMoura
Created April 22, 2024 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DouglasdeMoura/22fc9fc7072839b6b5a7c9f42630b29d to your computer and use it in GitHub Desktop.
Save DouglasdeMoura/22fc9fc7072839b6b5a7c9f42630b29d to your computer and use it in GitHub Desktop.
Check if a string is balanced
/**
* Check if given string is balanced, i.e., if it has the same number of open and close delimiters.
* The following delimiters are considered: '(', ')', '[', ']', '{', '}'.
* A string with no delimiters is considered balanced.
*
* @link https://twitter.com/coproduto/status/1782352142050775113
* @param str {String} to check if it is balanced
* @returns {Boolean}
*/
export function isBalanced(str) {
const stack = []
const openDelimiters = ['(', '[', '{']
const closeDelimiters = [')', ']', '}']
for (let i = 0; i < str.length; i++) {
const char = str[i]
if (openDelimiters.includes(char)) {
stack.push(char)
continue
}
if (closeDelimiters.includes(char)) {
if (stack.length === 0) {
return false
}
const lastOpenDelimiter = stack.pop()
if (!lastOpenDelimiter) {
return false
}
const correspondingCloseDelimiter = closeDelimiters[openDelimiters.indexOf(lastOpenDelimiter)]
if (char !== correspondingCloseDelimiter) {
return false
}
}
}
return stack.length === 0;
}
import assert from 'node:assert'
import { describe, it } from 'node:test'
import { isBalanced } from './challenge.js'
describe('isBalanced', () => {
it('should return true for a balanced string', () => {
assert.strictEqual(isBalanced('abcd'), true)
assert.strictEqual(isBalanced('(abcd)'), true)
assert.strictEqual(isBalanced('(abc[%def])'), true)
assert.strictEqual(isBalanced('$(abc[de]fg{hi}jk)%//'), true)
})
it('should return false for an unbalanced string', () => {
assert.strictEqual(isBalanced('(abcd'), false)
assert.strictEqual(isBalanced('abcd]'), false)
assert.strictEqual(isBalanced('(abc]d'), false)
assert.strictEqual(isBalanced('(({abc})'), false)
assert.strictEqual(isBalanced('(ab[cd)ef]'), false)
assert.strictEqual(isBalanced('{ab(cd}ef)'), false)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment