|
@@ -54,6 +54,17 @@ module.exports = class Computer {
|
|
|
inputFromConsole: options.inputFromConsole ?? false,
|
|
|
outputToConsole: options.outputToConsole ?? false,
|
|
|
};
|
|
|
+
|
|
|
+ /**
|
|
|
+ * An input value provided at runtime
|
|
|
+ *
|
|
|
+ * This value will be passed to the first INPUT opcode made by the computer,
|
|
|
+ * and will then be cleared. If the program being ran tries to make another
|
|
|
+ * call to INPUT, and `options.inputFromConsole` is false, then an error
|
|
|
+ * will be thrown.
|
|
|
+ * @type {number}
|
|
|
+ */
|
|
|
+ this.runtimeInput = null;
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -73,6 +84,26 @@ module.exports = class Computer {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * Run the computer with an initial input value
|
|
|
+ *
|
|
|
+ * Runs opcodes on the stack until either the a HALT command is
|
|
|
+ * encountered, or an error is thrown. Stores the input to be used
|
|
|
+ * by the first INPUT opcode encountered.
|
|
|
+ * @param {number} input The input value to initialize the comptuer with.
|
|
|
+ * @returns {void}
|
|
|
+ */
|
|
|
+ async RunWithInput(input) {
|
|
|
+ this.runtimeInput = input;
|
|
|
+ while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
|
|
|
+ if (this.options.tickRate) {
|
|
|
+ // Sleep
|
|
|
+ // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
|
|
|
+ await new Promise(resolve => setTimeout(resolve, this.options.tickRate));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* Execute a call using the provided opcode
|
|
|
*
|
|
@@ -208,9 +239,18 @@ module.exports = class Computer {
|
|
|
|
|
|
let userInput;
|
|
|
|
|
|
- do {
|
|
|
- userInput = Number(prompt("Please enter a number: "));
|
|
|
- } while (Number.isNaN(userInput));
|
|
|
+ if (this.runtimeInput !== null) {
|
|
|
+ userInput = this.runtimeInput;
|
|
|
+ this.runtimeInput = null;
|
|
|
+ }
|
|
|
+ else if (this.options.inputFromConsole) {
|
|
|
+ do {
|
|
|
+ userInput = Number(prompt("Please enter a number: "));
|
|
|
+ } while (Number.isNaN(userInput));
|
|
|
+ }
|
|
|
+ else {
|
|
|
+ throw new Error("No input found");
|
|
|
+ }
|
|
|
|
|
|
this.stack.Put(outputPosition, userInput);
|
|
|
}
|