Переглянути джерело

Update Stack to use Parameter Modes

Update the Stack.Get function to take a Parameter Mode as an argument.
It will then use the value of that to change whether it gets the current
value from the stack, or the value at that value's position.
ApisNecros 1 рік тому
батько
коміт
1140b77710
1 змінених файлів з 24 додано та 2 видалено
  1. 24 2
      IntComp/Stack.js

+ 24 - 2
IntComp/Stack.js

@@ -1,3 +1,5 @@
+const ComputerParameterMode = require("./ComputerParameterMode");
+
 /**
  * The stack, or memory, for the Intcode Computer
  *
@@ -26,19 +28,39 @@ module.exports = class Stack {
         this.pointer--;
     }
 
+    /**
+     * Get the value from the stack by the pointer's current position
+     *
+     * @param {number} [parameterMode=0] The Parameter Mode to use to retrieve the value
+     * @returns {number} The value at the current pointer position on the stack
+     */
+    Get(parameterMode = ComputerParameterMode.POSITION_MODE) {
+        let value = this._stack[this.pointer];
+        if (parameterMode == ComputerParameterMode.POSITION_MODE) {
+            value = this._stack[value];
+        }
+
+        return value;
+    }
+
     /**
      * Get a value at a given index on the stack
      *
      * @param {number} index The index of the value to retrieve
+     * @param {number} [parameterMode=0] The Parameter Mode to use to retrieve the value
      * @returns {number} The value at the given index, or 0 if the index hasn't been defined yet
      */
-    GetAtIndex(index) {
+    GetAtIndex(index, parameterMode = ComputerParameterMode.POSITION_MODE) {
         if (index == null || Number.isNaN(index) || !Number.isInteger(index)) {
             throw new TypeError("index must be an integer");
         }
 
         try {
-            return index !== null ? this._stack[index] : this._stack[this.pointer];
+            let value = this._stack[index];
+            if (parameterMode == ComputerParameterMode.POSITION_MODE) {
+                value = this._stack[value];
+            }
+            return value;
         }
         catch (e) {
             return 0;