Stack.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * The stack, or memory, for the Intcode Computer
  3. *
  4. * @author Apis Necros
  5. */
  6. module.exports = class Stack {
  7. constructor(stack) {
  8. this.pointer = 0;
  9. this._stack = stack;
  10. }
  11. /**
  12. * Move the stack's pointer to the right by 1
  13. * @returns {void}
  14. */
  15. Next() {
  16. this.pointer++;
  17. return this;
  18. }
  19. /**
  20. * Move the stack's pointer to the left by 1
  21. * @returns {void}
  22. */
  23. Prev() {
  24. this.pointer--;
  25. }
  26. /**
  27. * Get a value at a given index on the stack
  28. *
  29. * @param {number} index The index of the value to retrieve
  30. * @returns {number} The value at the given index, or 0 if the index hasn't been defined yet
  31. */
  32. GetAtIndex(index) {
  33. if (index == null || Number.isNaN(index) || !Number.isInteger(index)) {
  34. throw new TypeError("index must be an integer");
  35. }
  36. try {
  37. return index !== null ? this._stack[index] : this._stack[this.pointer];
  38. }
  39. catch (e) {
  40. return 0;
  41. }
  42. }
  43. /**
  44. * Use the value at the current pointer to get a value at another position
  45. *
  46. * This is essentially shorthand for `stack.Get(stack.Get())`
  47. *
  48. * @returns {number} The value at the index given by the pointer's current position
  49. */
  50. GetUsingStackValue() {
  51. return this.Get(this._stack[this.pointer]);
  52. }
  53. /**
  54. * Push a new value onto the end of the stack
  55. *
  56. * @param {number} value The value to add
  57. * @returns {void}
  58. */
  59. Push(value) {
  60. this._stack[++this.pointer] = value;
  61. }
  62. /**
  63. * Pop a value off the end of the stack
  64. *
  65. * @returns {number}
  66. * @returns {void}
  67. */
  68. Pop() {
  69. return this._stack.pop();
  70. }
  71. /**
  72. * Overwrite the value at a given index with a new value
  73. *
  74. * The index need not be defined
  75. *
  76. * @param {number} index The index on the stack to write a value to
  77. * @param {number} value The value to write to that position
  78. * @returns {void}
  79. */
  80. Put(index, value) {
  81. this._stack[index] = value;
  82. }
  83. /**
  84. * Return the whole stack
  85. *
  86. * @returns {number[]} The current stack
  87. */
  88. Dump() {
  89. return this._stack;
  90. }
  91. };