-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.brackets.js
More file actions
42 lines (36 loc) · 1.06 KB
/
string.brackets.js
File metadata and controls
42 lines (36 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* @title: String verify brackets
* @description: simple function to verify closing brackets
* @author: Thorsten Kober
* @email: [email protected]
*/
function bracketsAreBalanced(str) {
const options = '[]{}()';
const stack = [];
let i;
let character;
let position;
for (i = 0; i < str.length; i++) {
character = str[i];
position = options.indexOf(character);
if (position === -1) {
continue; // eslint-disable-line
}
if (position % 2 === 0) {
stack.push(position + 1);
} else if (stack.pop() !== position) {
return false;
}
}
return stack.length === 0;
}
// npx jest algorithms/string/string.brackets.js
test('bracketsAreBalanced()', () => {
expect(bracketsAreBalanced('{}([])')).toBe(true);
expect(bracketsAreBalanced('{{')).toBe(false);
expect(bracketsAreBalanced('[(])')).toBe(false);
expect(bracketsAreBalanced('{}([])')).toBe(true);
expect(bracketsAreBalanced('([}])')).toBe(false);
expect(bracketsAreBalanced('([])')).toBe(true);
expect(bracketsAreBalanced('()[]{}[][]')).toBe(true);
});