123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- /**
- * The stack, or memory, for the Intcode Computer
- *
- * @author Apis Necros
- */
- module.exports = class Stack {
- constructor(stack) {
- this.pointer = 0;
- this._stack = stack;
- }
- /**
- * Move the stack's pointer to the right by 1
- * @returns {void}
- */
- Next() {
- this.pointer++;
- return this;
- }
- /**
- * Move the stack's pointer to the left by 1
- * @returns {void}
- */
- Prev() {
- this.pointer--;
- }
- /**
- * Get a value from the stack
- *
- * If an index isn't given, retrieves the value at the current
- * location of the pointer
- *
- * @param {?number} index The index of the value to retrieve
- * @returns {number} The value at the given index, or 0
- */
- Get(index = null) {
- 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];
- }
- catch (e) {
- return 0;
- }
- }
- /**
- * Use the value at the current pointer to get a value at another position
- *
- * This is essentially shorthand for `stack.Get(stack.Get())`
- *
- * @returns {number} The value at the index given by the pointer's current position
- */
- GetUsingStackValue() {
- return this.Get(this._stack[this.pointer]);
- }
- /**
- * Push a new value onto the end of the stack
- *
- * @param {number} value The value to add
- * @returns {void}
- */
- Push(value) {
- this._stack[++this.pointer] = value;
- }
- /**
- * Pop a value off the end of the stack
- *
- * @returns {number}
- * @returns {void}
- */
- Pop() {
- return this._stack.pop();
- }
- /**
- * Overwrite the value at a given index with a new value
- *
- * The index need not be defined
- *
- * @param {number} index The index on the stack to write a value to
- * @param {number} value The value to write to that position
- * @returns {void}
- */
- Put(index, value) {
- this._stack[index] = value;
- }
- /**
- * Return the whole stack
- *
- * @returns {number[]} The current stack
- */
- Dump() {
- return this._stack;
- }
- };
|