]> git.ardis.lu - random-word-generator/commitdiff
Add validation for words and length arguments
authorArdis Lu <ardisglu@gmail.com>
Tue, 5 Jul 2022 04:01:55 +0000 (21:01 -0700)
committerArdis Lu <ardisglu@gmail.com>
Tue, 5 Jul 2022 04:01:55 +0000 (21:01 -0700)
main.ts

diff --git a/main.ts b/main.ts
index 53db562b21249e95c25c7c05a555e8c7569cfdcd..78499660677cf24ed69226914bfd65a362f2cecc 100644 (file)
--- a/main.ts
+++ b/main.ts
@@ -8,10 +8,23 @@ const { words, separator, length } = parse(Deno.args, {
   }
 });
 
+function abort(error: Error) {
+  console.error(error);
+  Deno.exit(1);
+}
+
+// Validate and process words argument
 const dictionary: string[] = [];
-await Deno.readTextFile(words).then(f => dictionary.push(...f.split(/\r?\n/)));
+await Deno.readTextFile(words)
+  .then(f => dictionary.push(...f.split(/\r?\n/)))
+  .catch(abort); // Will throw if an invalid file path is given
 
-const rand = new Uint16Array(parseInt(length));
+// Validate and process length argument
+const len = parseInt(length);
+if (isNaN(len)) {
+  abort(new TypeError(`${length} is not a number.`));
+}
+const rand = new Uint16Array(len);
 crypto.getRandomValues(rand);
 
 const output: string[] = [];
This page took 0.041419 seconds and 4 git commands to generate.