Reputation: 35
I have the following problem, I have a function that detects when a message has arrived, and when the message contains the prefix "#" for example "Hello I mean #LOL" it only gets the "LOL". And it works very well indeed, but now I want it to be able to detect not only the "#" prefix but also the "$" prefix for example $ MONEY. The first thing that occurred to me was to literally copy the entire function and declare for example prefixD = "$". The problem is that I have a lot of repeated / duplicated code, and I think it is not good to do it like that, what would be the correct way to do it? I leave my code here (Which works, but it has a lot of duplicate code)
client.on("message", function consigue(msg) {
const prefix = "#";
if (!msg.content.includes(prefix)) return;
const pattern = new RegExp(prefix + "([a-z]+)", "i");
const getMatch = (str) => str.match(pattern)?.[1];
TRADE_OUT = getMatch(msg.content);
if (TRADE_OUT != "") {
// some here
}
});
client.on("message", function consigueD(msg) {
const prefixD = "$";
if (!msg.content.includes(prefixD)) return;
function escapeRegex(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
const pattern = new RegExp(escapeRegex(prefixD) + '([a-z]+)', 'i');
const getMatch = (str) => str.match(pattern)?.[1];
TRADE_OUT = getMatch(msg.content);
if (TRADE_OUT != "") {
// The same some here
}
});
For example I would like to replace that
if (TRADE_OUT != "") {
}
which is repeated in the two functions and is exactly the same code , and everything it has inside as it is done with the functions in the modules, which are declared only as name (); and they already execute all the code they have inside, and you can use it as many times as you want.
What would be the best way to do everything in the same function? I have tried with || , and in many other ways but the truth is I'm not very good with this topic
Upvotes: 0
Views: 294
Reputation: 122
You could make a factory.
let handlerFactory = flag => {
return msg => {
const prefix = flag
...
}
}
Then you would do
client.on("message", handlerFactory("X"))
where X is either "$" or "#".
EDIT: If you meant "just the part within the TRADE_OUT-bit is a duplicate" then just take that, put it in a function declared before the handlers and call that from within the TRADE_OUT-bit.
Upvotes: 1