feat(handler): adding higher-order-function wrappers to increase readability and shorten code

Experimenting with functional paradigm to hopefully reduce redundancy and try improving readability,
shorten code, and create a cleaner code base
This commit is contained in:
jacoobes
2022-02-15 16:09:42 -06:00
parent 1473f309fa
commit 0f0b0fb61c
3 changed files with 20 additions and 6 deletions

View File

@@ -12,8 +12,9 @@ import type {
} from 'discord.js';
import { Ok, Result, None, Some } from 'ts-results';
import { isBot, hasPrefix, fmt } from './utilities/messageHelpers';
import { isNotFromBot, hasPrefix, fmt } from './utilities/messageHelpers';
import Logger from './logger';
import { AllTrue } from './utilities/higherOrders';
/**
* @class
@@ -44,7 +45,9 @@ export class Handler {
})
.on('messageCreate', async (message: Message) => {
if (isBot(message) || !hasPrefix(message, this.prefix)) return;
const isExecutable = AllTrue( isNotFromBot, hasPrefix );
if(!isExecutable(message, this.prefix)) return;
if (message.channel.type === 'DM') return; // TODO: Handle dms
const tryFmt = fmt(message, this.prefix);

View File

@@ -0,0 +1,11 @@
import type { Message } from "discord.js";
type MsgFnArgs = [msgOrInter: Message, prefix?: string];
type MsgFn = (...args: MsgFnArgs) => boolean;
export function AllTrue(...fn : MsgFn[]) {
return (message: Message, prefix: string) => {
return fn.every(f => f(message, prefix) === true)
}
}

View File

@@ -6,8 +6,8 @@ import type { Message } from 'discord.js';
* @example
* isBot(message) ? 'yes it is a bot' : 'no it is not a bot';
*/
export function isBot(message: Message) {
return message.author.bot;
export function isNotFromBot(message: Message) {
return !message.author.bot;
}
/**
* Checks if the message **starts** with the prefix
@@ -17,8 +17,8 @@ export function isBot(message: Message) {
* @example
* hasPrefix(message, '!') ? 'yes it does' : 'no it does not';
*/
export function hasPrefix(message: Message, prefix: string) {
return message.content.slice(0, prefix.length).toLowerCase().trim() === prefix;
export function hasPrefix(message: Message, prefix?: string) {
return message.content.startsWith(prefix!);
}
/**
* Removes the first character(s) _[depending on prefix length]_ of the message