Browse Source

Implement ]

Added the ability to collapse stacks using the ] instruction.
ApisNecros 1 year ago
parent
commit
32c5adf02a
1 changed files with 25 additions and 2 deletions
  1. 25 2
      starfish.js

+ 25 - 2
starfish.js

@@ -318,8 +318,9 @@ class CodeBox {
                     this.SpliceStack(this.stacks[this.curr_stack].Pop());
                     break;
                 }
-                // case "]":
-                //     break;
+                case "]":
+                    this.CollapseStack();
+                    break;
                 case "I": {
                     this.curr_stack++;
                     if (this.curr_stack >= this.stacks.length) {
@@ -558,6 +559,28 @@ class CodeBox {
 
         this.curr_stack++;
     }
+    /**
+     * Collapses the current stack onto the one below it
+     *
+     * If the current stack is the only one, it is replaced with a blank stack
+     */
+    CollapseStack() {
+        // Undefined behavior collapsing the first stack down when there are other stacks available
+        if (this.curr_stack == 0 && this.stacks.length != 1) {
+            throw new Error();
+        }
+
+        if (this.curr_stack == 0) {
+            this.stacks = [new Stack()];
+        }
+        else {
+            const collapsed = this.stacks.splice(this.curr_stack, 1).pop();
+            this.curr_stack--;
+            const currStackCount = this.stacks[this.curr_stack].stack.length;
+
+            this.stacks[this.curr_stack].stack.splice(currStackCount, 0, ...collapsed.stack);
+        }
+    }
 
     /**
      * Implement `