-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathstream.js
50 lines (44 loc) · 1.28 KB
/
stream.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
const START_GARBAGE = '<';
const END_GARBAGE = '>';
const START_GROUP = '{';
const END_GROUP = '}';
const IGNORE_SYMBOL = '!';
const GROUP_SEPARATOR = ',';
class Stream {
constructor(stream) {
let parsed_stream = this.parse(stream);
this.score = parsed_stream.score;
this.garbageCleaned = parsed_stream.garbageCleaned;
}
parse(stream) {
let group = 0;
let groups = [];
let garbage = false;
let total_garbage = 0;
for (let i = 0; i < stream.length; i++) {
let char = stream[i];
if (!garbage) {
if (char === START_GROUP) {
++group;
} else if (char === END_GROUP) {
groups.push(group--);
} else if (char === START_GARBAGE) {
garbage = true;
}
} else {
if (char === IGNORE_SYMBOL) {
i++;
} else if (char === END_GARBAGE) {
garbage = false;
} else {
total_garbage++;
}
}
}
return {
score: groups.reduce((a, b) => a + b, 0),
garbageCleaned: total_garbage,
};
}
}
module.exports = Stream;