Created
April 22, 2024 16:37
-
-
Save DouglasdeMoura/22fc9fc7072839b6b5a7c9f42630b29d to your computer and use it in GitHub Desktop.
Check if a string is balanced
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
/** | |
* 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; | |
} |
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
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