123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- const Stack = require("./Stack");
- module.exports = class Computer {
- constructor(stack) {
- this.stack = new Stack(stack);
- this.OPCODES = {
- ADD: 1,
- MULTIPLY: 2,
- HALT: 99,
- };
- }
-
- Run() {
-
- while (this.Execute(this.stack.Get()) === true) { }
- }
-
- Execute(opcode) {
-
- let status = true;
- switch (opcode) {
- case this.OPCODES.ADD: {
- const operandLeft = this.stack.Next().GetUsingStackValue();
- const operandRight = this.stack.Next().GetUsingStackValue();
- const position = this.stack.Next().Get();
- this.Operation_Add(operandLeft, operandRight, position);
- break;
- }
- case this.OPCODES.MULTIPLY: {
- const operandLeft = this.stack.Next().GetUsingStackValue();
- const operandRight = this.stack.Next().GetUsingStackValue();
- const position = this.stack.Next().Get();
- this.Operation_Multiply(operandLeft, operandRight, position);
- break;
- }
- case this.OPCODES.HALT:
- status = false;
- break;
- default:
- throw Error(`Opcode ${opcode} not found`);
- }
- this.stack.Next();
- return status;
- }
-
- Operation_Add(operandLeft, operandRight, outputPosition) {
- const newValue = operandLeft + operandRight;
- this.stack.Put(outputPosition, newValue);
- }
-
- Operation_Multiply(operandLeft, operandRight, outputPosition) {
- const newValue = operandLeft * operandRight;
- this.stack.Put(outputPosition, newValue);
- }
-
- DumpMemory() {
- console.log(this.stack.Dump());
- }
- };
|