11const { SlashCommandBuilder } = require ( "@discordjs/builders" ) ;
2- const { isNaN } = require ( "mathjs" ) ;
3- const { Util } = require ( "discord.js" ) ;
42const math = require ( "mathjs" ) ;
3+ const { Util } = require ( "discord.js" ) ;
54
65const illegalPhraseRegexes = [ / ` / g, / @ / g] ;
76
87const isIllegalCharactersPresent = ( expression ) => {
98 return illegalPhraseRegexes . some ( ( regex ) => regex . test ( expression ) ) ;
109} ;
1110
11+ const tryCompileAndEvaluate = ( eqnString ) => {
12+ try {
13+ const equationObj = math . compile ( eqnString ) ;
14+ if ( ! equationObj ) {
15+ throw Error ;
16+ }
17+
18+ const equationOutcome = equationObj . evaluate ( ) ;
19+
20+ return {
21+ success : true ,
22+ equationOutcome,
23+ } ;
24+
25+ } catch ( e ) {
26+ return {
27+ success : false ,
28+ message : "Could not compile. The equation is invalid." ,
29+ ephemeral : true ,
30+ } ;
31+ }
32+ } ;
33+
1234const evaluate = ( equationString , target ) => {
1335 if ( isIllegalCharactersPresent ( equationString ) ) {
1436 return {
@@ -18,18 +40,18 @@ const evaluate = (equationString, target) => {
1840 } ;
1941 }
2042
21- const equationObj = math . compile ( equationString ) ;
22- if ( ! equationObj ) {
43+ const evaluationOutcome = tryCompileAndEvaluate ( equationString ) ;
44+ if ( ! evaluationOutcome . success ) {
2345 return {
2446 success : false ,
25- message : "Could not compile. The equation is invalid." ,
47+ message : evaluationOutcome . message ,
2648 ephemeral : true ,
2749 } ;
2850 }
51+ const { equationOutcome } = evaluationOutcome ;
2952
30- const equationOutcome = equationObj . evaluate ( ) ;
3153 const outcomeAsNumber = Number ( equationOutcome ) ;
32- if ( isNaN ( outcomeAsNumber ) ) {
54+ if ( math . isNaN ( outcomeAsNumber ) ) {
3355 return {
3456 success : false ,
3557 message : "Could not compile. The equation does not evaluate to a number." ,
@@ -38,16 +60,17 @@ const evaluate = (equationString, target) => {
3860 }
3961
4062 return outcomeAsNumber == target
41- ? {
42- success : true ,
43- message : `Correct! \`${ equationString } \` = ${ target } , which is equal to the target of ${ target } .` ,
44- ephemeral : false ,
45- }
46- : {
47- success : false ,
48- message : `Incorrect. \`${ equationString } \` = ${ outcomeAsNumber } , which is not equal to the target of ${ target } .` ,
49- ephemeral : false ,
50- } ;
63+ ? {
64+ success : true ,
65+ message : `Correct! \`${ equationString } \` = ${ target } , which is equal to the target.` ,
66+ ephemeral : false ,
67+ }
68+ : {
69+ success : false ,
70+ message : `Incorrect. \`${ equationString } \` = ${ outcomeAsNumber } , which is not equal to the target of ${ target } .` ,
71+ ephemeral : false ,
72+ } ;
73+
5174} ;
5275
5376module . exports = {
@@ -75,3 +98,4 @@ module.exports = {
7598 } ) ;
7699 } ,
77100} ;
101+
0 commit comments