Stack.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 from the stack
  28. *
  29. * If an index isn't given, retrieves the value at the current
  30. * location of the pointer
  31. *
  32. * @param {?number} index The index of the value to retrieve
  33. * @returns {number} The value at the given index, or 0
  34. */
  35. Get(index = null) {
  36. if (index !== null && (Number.isNaN(index) || !Number.isInteger(index))) {
  37. throw new TypeError("index must be an integer");
  38. }
  39. try {
  40. return index !== null ? this._stack[index] : this._stack[this.pointer];
  41. }
  42. catch (e) {
  43. return 0;
  44. }
  45. }
  46. /**
  47. * Use the value at the current pointer to get a value at another position
  48. *
  49. * This is essentially shorthand for `stack.Get(stack.Get())`
  50. *
  51. * @returns {number} The value at the index given by the pointer's current position
  52. */
  53. GetUsingStackValue() {
  54. return this.Get(this._stack[this.pointer]);
  55. }
  56. /**
  57. * Push a new value onto the end of the stack
  58. *
  59. * @param {number} value The value to add
  60. * @returns {void}
  61. */
  62. Push(value) {
  63. this._stack[++this.pointer] = value;
  64. }
  65. /**
  66. * Pop a value off the end of the stack
  67. *
  68. * @returns {number}
  69. * @returns {void}
  70. */
  71. Pop() {
  72. return this._stack.pop();
  73. }
  74. /**
  75. * Overwrite the value at a given index with a new value
  76. *
  77. * The index need not be defined
  78. *
  79. * @param {number} index The index on the stack to write a value to
  80. * @param {number} value The value to write to that position
  81. * @returns {void}
  82. */
  83. Put(index, value) {
  84. this._stack[index] = value;
  85. }
  86. /**
  87. * Return the whole stack
  88. *
  89. * @returns {number[]} The current stack
  90. */
  91. Dump() {
  92. return this._stack;
  93. }
  94. };