Browse Source

Fix duration parsing in contest

ghorsington 5 years ago
parent
commit
f1dec20262
1 changed files with 14 additions and 21 deletions
  1. 14 21
      bot/src/commands/contest.ts

+ 14 - 21
bot/src/commands/contest.ts

@@ -1,8 +1,7 @@
 import { ICommand } from "./command";
-import { Dict, NeighBuilder } from "../util";
+import { Dict } from "../util";
 import { ReactionCollector, Message } from "discord.js";
 import yaml from "yaml";
-import { client } from "src/client";
 import { getRepository } from "typeorm";
 import { Contest } from "@db/entity/Contest";
 import { isNumber } from "util";
@@ -39,25 +38,22 @@ const DURATION_MULTIPLIERS : Dict<number> = {
     "y": 365 * 24 * 60 * 60 * 1000
 };
 
+const DURATION_REGEX_STR = `(\\d+) ?(${Object.keys(DURATION_MULTIPLIERS).join("|")})`;
+const DURATION_REGEX = new RegExp(DURATION_REGEX_STR, "i");
+
 function parseDuration(duration: string) : number | undefined {
-    // Time to eat...
-    let numNB = new NeighBuilder();
-    
-    let chIndex = 0;
-    for(; chIndex < duration.length; chIndex++) {
-        let c = duration.charAt(chIndex);
-        if(isNumber(c))
-            numNB.append(c);
-        else
-            break;
-    }
+    let match = DURATION_REGEX.exec(duration);
 
-    let unit = duration.substr(chIndex).trim().toLowerCase();
+    if(match.length == 0)
+        return undefined;
 
-    if(!(unit in DURATION_MULTIPLIERS))
+    let num = match[1];
+    if(!isNumber(num))
         return undefined;
 
-    return +numNB * DURATION_MULTIPLIERS[unit];
+    let unit = match[2];
+
+    return +num * DURATION_MULTIPLIERS[unit];
 }
 
 async function createContest(msg: Message, info: ContestCreationOptions) {
@@ -94,10 +90,9 @@ async function createContest(msg: Message, info: ContestCreationOptions) {
     await msg.channel.send(`${msg.author.toString()} Started contest (ID: ${contest.id})`);
 }
 
-const d = <ICommand>{
+export default <ICommand>{
     commands: [
         {
-            //\s+in:\s*([^\s]+)\s+duration:\s(\d+ ?(s|d|m|y))\s+announce_winners:\s*(true|false)\s+vote_reaction:\s*([^\s])
             pattern: "create contest",
             action: async (m, contents) => {
                 let message = contents.substr("create contest".length);
@@ -144,6 +139,4 @@ const d = <ICommand>{
         }
     ],
     onStart: init,
-};
-
-export default {};
+};