-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsyntax.js
67 lines (58 loc) · 1.04 KB
/
syntax.js
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
const open_chars = new Set(['(', '[', '{', '<']);
const closed_chars = new Set([')', ']', '}', '>']);
const CORRUPTED_SCORE = {
')': 3,
']': 57,
'}': 1197,
'>': 25137,
};
const INCOMPLETE_SCORE = {
')': 1,
']': 2,
'}': 3,
'>': 4,
};
const chars = {
'(': ')',
'[': ']',
'{': '}',
'<': '>',
};
const getLineStatus = (_line) => {
const line = [..._line];
const stack = [line.shift()];
while (line.length > 0) {
const next_char = line.shift();
const head = stack[stack.length - 1];
// `if (chars['{'] === '}')`
if (chars[head] === next_char) {
stack.pop();
} else if (open_chars.has(next_char)) {
stack.push(next_char);
} else {
// A closing char that doesn't match
return {
error: true,
code: `Expected ${chars[head]}, but found ${next_char} instead.`,
char: next_char,
};
}
}
if (stack.length > 0) {
return {
incomplete: true,
stack,
};
}
return {
complete: true,
};
};
module.exports = {
getLineStatus,
CORRUPTED_SCORE,
INCOMPLETE_SCORE,
open_chars,
closed_chars,
chars,
};