Explorar o código

Add implementation for tickSleep option

The tickSleep option now works. To accomplish this, there is a new
version of the run function, runTimed. By setting tickSleep, the run
process is bypassed to runTimed with runs the swim function on a
setInterval. If swim finishes, it clears the interval.
ApisNecros hai 1 ano
pai
achega
3099057975
Modificáronse 1 ficheiros con 15 adicións e 0 borrados
  1. 15 0
      src/codebox.ts

+ 15 - 0
src/codebox.ts

@@ -3,6 +3,7 @@ import { InstructionPointer } from "./pointer.js";
 import { EmptyCodeBoxError, FailedToParseCodeBoxError } from "./errors.js";
 import { CodeBoxOptions, OrdinalDirection } from "./types.js";
 import { charToDecimal, deepClone } from "./common.js";
+import { Node } from "typescript";
 
 export class CodeBox {
     /**
@@ -95,6 +96,10 @@ export class CodeBox {
 
         // Set the default output callback to log to the console
         this.options.outputCallback ??= console.log;
+        this.options.tickSleep ??= 0;
+        if (this.options.tickSleep < 0) {
+            throw new RangeError("the tickSleep option must be a float >= 0");
+        }
         // Initialize the default debug options if none were set
         this.options.debug ??= {};
         this.options.debug.print ??= {}
@@ -107,6 +112,7 @@ export class CodeBox {
      * Begin execution of the CodeBox
      */
     public run() {
+        if (this.options.tickSleep) { return this.runTimed(); }
         let finished = false;
 
         while (!finished) {
@@ -114,6 +120,15 @@ export class CodeBox {
         }
     }
 
+    private runTimed() {
+        let intervalID: NodeJS.Timeout;
+        intervalID = setInterval(() => {
+            if (this.swim()) {
+                clearInterval(intervalID);
+            }
+        }, this.options.tickSleep as number * 1000);
+    }
+
     /**
      * Execute one step inside the codebox
      *