Browse Source

Add Parameter Mode handling to add & multiply

Through the new Operation_ParseOperands function, the add and multiply
operations now work in Position Mode and Immediate Mode.
ApisNecros 1 năm trước cách đây
mục cha
commit
645658d1fc
1 tập tin đã thay đổi với 17 bổ sung0 xóa
  1. 17 0
      IntComp/Computer.js

+ 17 - 0
IntComp/Computer.js

@@ -75,6 +75,20 @@ module.exports = class Computer {
         return status;
     }
 
+    /**
+     * Parse operands based on the current parameter mode
+     *
+     * When the int computer is in Immediate Mode, the values are returned
+     * as-is. When in Position Mode, the operands are used as memory
+     * addresses, and the values at those addresses are returned instead.
+     *
+     * @returns {number[]} The parsed list of operands
+     */
+    _ParseOperands(...operands) {
+        if (this.parameterMode == ComputerParameterMode.IMMEDIATE_MODE) { return operands; }
+        return operands.map((operand) => this.stack.Get(operand));
+    }
+
     /**
      * Execute the Add opcode
      *
@@ -87,6 +101,7 @@ module.exports = class Computer {
      * @returns {void}
      */
     Operation_Add(operandLeft, operandRight, outputPosition) {
+        [operandLeft, operandRight] = this._ParseOperands(operandLeft, operandRight);
         const newValue = operandLeft + operandRight;
         this.stack.Put(outputPosition, newValue);
     }
@@ -103,6 +118,8 @@ module.exports = class Computer {
      * @returns {void}
      */
     Operation_Multiply(operandLeft, operandRight, outputPosition) {
+        [operandLeft, operandRight] = this._ParseOperands(operandLeft, operandRight);
+
         const newValue = operandLeft * operandRight;
         this.stack.Put(outputPosition, newValue);
     }