forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbraceCounter.ts
More file actions
71 lines (63 loc) · 2.02 KB
/
braceCounter.ts
File metadata and controls
71 lines (63 loc) · 2.02 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IToken, TokenType } from './types';
class BracePair {
public readonly openBrace: TokenType;
public readonly closeBrace: TokenType;
constructor(openBrace: TokenType, closeBrace: TokenType) {
this.openBrace = openBrace;
this.closeBrace = closeBrace;
}
}
class Stack {
private store: IToken[] = [];
public push(val: IToken) {
this.store.push(val);
}
public pop(): IToken | undefined {
return this.store.pop();
}
public get length(): number {
return this.store.length;
}
}
export class BraceCounter {
private readonly bracePairs: BracePair[] = [
new BracePair(TokenType.OpenBrace, TokenType.CloseBrace),
new BracePair(TokenType.OpenBracket, TokenType.CloseBracket),
new BracePair(TokenType.OpenCurly, TokenType.CloseCurly)
];
private braceStacks: Stack[] = [new Stack(), new Stack(), new Stack()];
public get count(): number {
let c = 0;
for (const s of this.braceStacks) {
c += s.length;
}
return c;
}
public isOpened(type: TokenType): boolean {
for (let i = 0; i < this.bracePairs.length; i += 1) {
const pair = this.bracePairs[i];
if (pair.openBrace === type || pair.closeBrace === type) {
return this.braceStacks[i].length > 0;
}
}
return false;
}
public countBrace(brace: IToken): boolean {
for (let i = 0; i < this.bracePairs.length; i += 1) {
const pair = this.bracePairs[i];
if (pair.openBrace === brace.type) {
this.braceStacks[i].push(brace);
return true;
}
if (pair.closeBrace === brace.type) {
if (this.braceStacks[i].length > 0) {
this.braceStacks[i].pop();
}
return true;
}
}
return false;
}
}