-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgive-take-regexp.js
44 lines (37 loc) · 1.09 KB
/
give-take-regexp.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
const heartsGive = ["<3", "❤"];
const heartsTake = ["</3"];
const heartsGiveRegexpGroup = `(${heartsGive.join("|")})`;
const heartsTakeRegexpGroup = `(${heartsTake.join("|")})`;
// Accepts: "❤ <nickname>", "<nickname>: ❤" and "<nickname>, ❤"
const makeRegexps = function (action, matchesList) {
const matches = `(${matchesList.join("|")})`
return {
action,
regexps: [
{group: 2, regexp: new RegExp(`^\\s*${matches}\\s+(\\S+)`)},
{group: 1, regexp: new RegExp(`^\\s*(\\S+)[:,]\\s+${matches}`)}
]
};
};
const queries = [
makeRegexps("give", heartsGive),
makeRegexps("take", heartsTake)
];
const query = function (message) {
for (const {action, regexps} of queries) {
for (const {group, regexp} of regexps) {
const found = message.match(regexp);
if (found !== null) {
return {
action,
target: found[group]
};
}
}
}
return {
action: "none",
target: ""
};
};
module.exports = query;