1
1
const { SlashCommandBuilder } = require ( "@discordjs/builders" ) ;
2
- const { isNaN } = require ( "mathjs" ) ;
3
- const { Util } = require ( "discord.js" ) ;
4
2
const math = require ( "mathjs" ) ;
3
+ const { Util } = require ( "discord.js" ) ;
5
4
6
5
const illegalPhraseRegexes = [ / ` / g, / @ / g] ;
7
6
8
7
const isIllegalCharactersPresent = ( expression ) => {
9
8
return illegalPhraseRegexes . some ( ( regex ) => regex . test ( expression ) ) ;
10
9
} ;
11
10
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
+
12
34
const evaluate = ( equationString , target ) => {
13
35
if ( isIllegalCharactersPresent ( equationString ) ) {
14
36
return {
@@ -18,18 +40,18 @@ const evaluate = (equationString, target) => {
18
40
} ;
19
41
}
20
42
21
- const equationObj = math . compile ( equationString ) ;
22
- if ( ! equationObj ) {
43
+ const evaluationOutcome = tryCompileAndEvaluate ( equationString ) ;
44
+ if ( ! evaluationOutcome . success ) {
23
45
return {
24
46
success : false ,
25
- message : "Could not compile. The equation is invalid." ,
47
+ message : evaluationOutcome . message ,
26
48
ephemeral : true ,
27
49
} ;
28
50
}
51
+ const { equationOutcome } = evaluationOutcome ;
29
52
30
- const equationOutcome = equationObj . evaluate ( ) ;
31
53
const outcomeAsNumber = Number ( equationOutcome ) ;
32
- if ( isNaN ( outcomeAsNumber ) ) {
54
+ if ( math . isNaN ( outcomeAsNumber ) ) {
33
55
return {
34
56
success : false ,
35
57
message : "Could not compile. The equation does not evaluate to a number." ,
@@ -38,16 +60,17 @@ const evaluate = (equationString, target) => {
38
60
}
39
61
40
62
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
+
51
74
} ;
52
75
53
76
module . exports = {
@@ -75,3 +98,4 @@ module.exports = {
75
98
} ) ;
76
99
} ,
77
100
} ;
101
+
0 commit comments