This repository has been archived by the owner on Feb 9, 2022. It is now read-only.
/
flags.ts
56 lines (42 loc) · 1.46 KB
/
flags.ts
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
import { TwitchFlag } from "../flag";
import { TwitchFlagList } from "../flags";
export function parseFlags(
messageText: string,
flagsSrc: string
): TwitchFlagList {
const flags: TwitchFlagList = [];
const regex = /^(,?(?:[0-9]+-[0-9]+:)(?:(?:[ISAP]\.[0-9]+\/?)+)?)+$/g;
const matchFlagsSrc = flagsSrc.match(regex);
if (flagsSrc.length <= 0 || matchFlagsSrc === null) {
return flags;
}
const messageCharacters = [...messageText];
for (const flagInstancesSrc of flagsSrc.split(",")) {
const [indexes, instancesSrc] = flagInstancesSrc.split(":", 2);
let [startIndex, endIndex] = indexes.split("-").map((s) => Number(s));
// to make endIndex exclusive
endIndex = endIndex + 1;
// flags tag can have wildly out-of-bounds indexes
if (startIndex < 0) {
startIndex = 0;
}
if (endIndex > messageCharacters.length) {
endIndex = messageCharacters.length;
}
const flagText = messageCharacters.slice(startIndex, endIndex).join("");
const categories: TwitchFlag["categories"] = [];
for (const instanceSrc of instancesSrc.split("/")) {
if (instanceSrc.length > 0) {
const [category, score] = instanceSrc.split(".");
categories.push({
category,
score: Number(score),
});
}
}
flags.push(new TwitchFlag(startIndex, endIndex, flagText, categories));
}
// sort by start index
flags.sort((a, b) => a.startIndex - b.startIndex);
return flags;
}