I wrote simple function for checking if string is balanced (with brackets ([{}])
). It takes a string argument and need to return boolean value (true if string is balanced and false if not).
const isBalanced = (string) => {
const arr = string.split('');
let open = [];
const openBrackets = {
'(': true,
'[': true,
'{': true,
};
const closedBrackets = {
')': '(',
']': '[',
'}': '{',
};
for (let i = 0, length = arr.length; i < length; i++) {
if (openBrackets[arr[i]]) {
open.push(arr[i]);
} else if (closedBrackets[arr[i]] && open.pop() !== closedBrackets[arr[i]]) {
return false;
}
}
return !open.length;
}
console.log(isBalanced('') === true);
console.log(isBalanced('()') === true);
console.log(isBalanced(')()') === false);
console.log(isBalanced(')(') === false);
console.log(isBalanced('()(()()()())') === true);
console.log(isBalanced('[](){}') === true);
console.log(isBalanced('[({})]') === true);
console.log(isBalanced('[(]{)}') === false);
console.log(isBalanced('const sth = () => { animal.sleep();') === false);
console.log(isBalanced('const sth = { bark: animal() }') === true);
Do you think that i could improve it somehow? Can you see any mistakes?