starfish.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. /**
  2. * The code box class
  3. */
  4. class CodeBox {
  5. constructor(codeBoxID, initialStackID, outputID) {
  6. /**
  7. * Possible vectors the pointer can move in
  8. * @type {Object}
  9. */
  10. this.directions = {
  11. NORTH: [ 0, -1],
  12. EAST: [ 1, 0],
  13. SOUTH: [ 0, 1],
  14. WEST: [-1, 0],
  15. };
  16. /**
  17. * The current vector of the pointer
  18. * @type {int[]}
  19. */
  20. this.curr_direction = this.directions.EAST;
  21. /**
  22. * The Set of instructions to execute
  23. *
  24. * Either a 1 or 2-dimensional array
  25. * @type {Array|Array[]}
  26. */
  27. this.box = [];
  28. /**
  29. * The farthest right the box goes
  30. * @type {int}
  31. */
  32. this.maxBoxWidth = 0;
  33. /**
  34. * The bottom of the box
  35. *
  36. * @type {int}
  37. */
  38. this.maxBoxHeight = 0;
  39. /**
  40. * The coordinates of the currently executing instruction inside the code box
  41. * @type {Object}
  42. */
  43. this.pointer = {
  44. X: 0,
  45. Y: 0,
  46. };
  47. /**
  48. * Was the instruction last moving in the left direction
  49. *
  50. * Used by the {@link Fisherman}
  51. * @type {boolean}
  52. */
  53. this.dirWasLeft = false;
  54. /**
  55. * Are we currently under the influence of the {@link Fisherman}
  56. * @type {boolean}
  57. */
  58. this.onTheHook = false;
  59. /**
  60. * Are we currently processing code box instructions as a string
  61. *
  62. * 0 when false, otherwise it holds the char code for string delimiter, either
  63. * 34 or 39
  64. *
  65. * @type {int}
  66. */
  67. this.stringMode = 0;
  68. /**
  69. * A list of stacks for the script to work with
  70. *
  71. * @type {Stack[]}
  72. */
  73. this.stacks = [new Stack()];
  74. /**
  75. * The index of the currently used stack
  76. *
  77. * @type {int}
  78. */
  79. this.curr_stack = 0;
  80. /**
  81. * The current date
  82. *
  83. * This value is updated every tick
  84. * @type {?Date}
  85. */
  86. this.datetime = null;
  87. /**
  88. * Assorted debug options
  89. *
  90. * @type {object}
  91. */
  92. this.debug= {
  93. print: {
  94. codeBox: false,
  95. stacks: false,
  96. }
  97. };
  98. this.codeBoxDOM = document.getElementById(codeBoxID);
  99. if(!this.codeBoxDOM) {
  100. throw new Error(`Failed to find textarea with ID: ${codeBoxID}`);
  101. }
  102. this.outputDOM = document.getElementById(outputID);
  103. if(!this.outputDOM) {
  104. throw new Error(`Failed to find textarea with ID: ${outputID}`);
  105. }
  106. this.initialStackDOM = document.getElementById(initialStackID);
  107. if(!this.initialStackDOM) {
  108. throw new Error(`Failed to find input with ID: ${initialStackID}`);
  109. }
  110. }
  111. /**
  112. * Parse the initial code box
  113. *
  114. * Transforms the textual code box into usable matrix
  115. */
  116. ParseCodeBox() {
  117. // Reset some fields for a clean run
  118. this.box = [];
  119. this.stacks = [new Stack()];
  120. this.curr_stack = 0;
  121. this.pointer = {X: 0, Y: 0};
  122. this.curr_direction = this.directions.EAST;
  123. this.outputDOM.value = "";
  124. console.clear();
  125. const cbRaw = this.codeBoxDOM.value;
  126. const rows = cbRaw.split("\n");
  127. let maxRowLength = 0;
  128. for(const row of rows) {
  129. const rowSplit = row.split("");
  130. // Store this for later processing
  131. while(rowSplit.length > maxRowLength) {
  132. maxRowLength = rowSplit.length
  133. }
  134. this.box.push(rowSplit);
  135. }
  136. this.EqualizeBoxWidth(maxRowLength);
  137. this.maxBoxWidth = maxRowLength - 1;
  138. this.maxBoxHeight = this.box.length - 1;
  139. if (this.initialStackDOM.value != "") {
  140. this.ParseInitialStack();
  141. }
  142. this.Run();
  143. }
  144. /**
  145. * Parse the value provided for the stack at run time
  146. */
  147. ParseInitialStack() {
  148. const separator = /(["'].+?["']|\d+)/g;
  149. const stackValues = this.initialStackDOM.value.split(separator).filter((v) => v.trim().length);
  150. for (const val of stackValues) {
  151. const intVal = parseInt(val);
  152. if (!Number.isNaN(intVal)) {
  153. this.stacks[this.curr_stack].Push(intVal);
  154. }
  155. else {
  156. let chars = val.substr(1, val.length - 2).split('');
  157. chars = chars.map((c) => dec(c));
  158. this.stacks[this.curr_stack].Push(chars);
  159. }
  160. }
  161. }
  162. /**
  163. * Prints the code box to the console
  164. */
  165. PrintCodeBox() {
  166. let output = "";
  167. for (let y = 0; y < this.box.length; y++) {
  168. for (let x = 0; x < this.box[y].length; x++) {
  169. let instruction = this.box[y][x];
  170. if (x == this.pointer.X && y == this.pointer.Y) {
  171. instruction = `*${instruction}*`;
  172. }
  173. output += `${instruction} `;
  174. }
  175. output += "\n";
  176. }
  177. console.log(output);
  178. }
  179. /**
  180. * Prints all stacks to the console
  181. */
  182. PrintStacks() {
  183. let output = "{\n";
  184. for (let i = 0; i < this.stacks.length; i++) {
  185. output += `\t${i}: ${JSON.stringify(this.stacks[i].stack)},\n`
  186. }
  187. output += "}";
  188. console.log(output);
  189. }
  190. /**
  191. * Make all the rows in the code box the same length
  192. *
  193. * All rows not long enough will have NOPs added until they're uniform in size.
  194. *
  195. * @param {int} [rowLength] The longest row in the code box
  196. */
  197. EqualizeBoxWidth(rowLength = null) {
  198. if(!rowLength) {
  199. for(const row of this.box) {
  200. if(row.length > rowLength) {
  201. rowLength = row.length;
  202. }
  203. }
  204. }
  205. for(const row of this.box) {
  206. while(row.length < rowLength) {
  207. row.push(" ");
  208. }
  209. }
  210. }
  211. /**
  212. * Print the value to the display
  213. *
  214. * @TODO Set up an actual display
  215. * @param {*} value
  216. */
  217. Output(value) {
  218. this.outputDOM.value += value;
  219. }
  220. /**
  221. * The main loop for the engine
  222. */
  223. Run() {
  224. let fin = null;
  225. try {
  226. while(!fin) {
  227. fin = this.Swim();
  228. }
  229. }
  230. catch(e) {
  231. console.error(e);
  232. }
  233. }
  234. Execute(instruction) {
  235. let output = null;
  236. try{
  237. switch(instruction) {
  238. // NOP
  239. case " ":
  240. break;
  241. // Numbers
  242. case "1":
  243. case "2":
  244. case "3":
  245. case "4":
  246. case "5":
  247. case "6":
  248. case "7":
  249. case "8":
  250. case "9":
  251. case "0":
  252. case "a":
  253. case "b":
  254. case "c":
  255. case "d":
  256. case "e":
  257. case "f":
  258. this.stacks[this.curr_stack].Push(parseInt(instruction, 16));
  259. break;
  260. // Operators
  261. case "+": {
  262. const x = this.stacks[this.curr_stack].Pop();
  263. const y = this.stacks[this.curr_stack].Pop();
  264. this.stacks[this.curr_stack].Push(y + x);
  265. break;
  266. }
  267. case "-": {
  268. const x = this.stacks[this.curr_stack].Pop();
  269. const y = this.stacks[this.curr_stack].Pop();
  270. this.stacks[this.curr_stack].Push(y - x);
  271. break;
  272. }
  273. case "*": {
  274. const x = this.stacks[this.curr_stack].Pop();
  275. const y = this.stacks[this.curr_stack].Pop();
  276. this.stacks[this.curr_stack].Push(y * x);
  277. break;
  278. }
  279. case ",": {
  280. const x = this.stacks[this.curr_stack].Pop();
  281. const y = this.stacks[this.curr_stack].Pop();
  282. this.stacks[this.curr_stack].Push(y / x);
  283. break;
  284. }
  285. case "%": {
  286. const x = this.stacks[this.curr_stack].Pop();
  287. const y = this.stacks[this.curr_stack].Pop();
  288. this.stacks[this.curr_stack].Push(y % x);
  289. break;
  290. }
  291. case "(": {
  292. const x = this.stacks[this.curr_stack].Pop();
  293. const y = this.stacks[this.curr_stack].Pop();
  294. this.stacks[this.curr_stack].Push(y < x ? 1 : 0);
  295. break;
  296. }
  297. case ")": {
  298. const x = this.stacks[this.curr_stack].Pop();
  299. const y = this.stacks[this.curr_stack].Pop();
  300. this.stacks[this.curr_stack].Push(y > x ? 1 : 0);
  301. break;
  302. }
  303. case "=": {
  304. const x = this.stacks[this.curr_stack].Pop();
  305. const y = this.stacks[this.curr_stack].Pop();
  306. this.stacks[this.curr_stack].push(y == x ? 1 : 0);
  307. break;
  308. }
  309. //String mode
  310. case "\"":
  311. case "'":
  312. this.stringMode = !!this.stringMode ? 0 : dec(instruction);
  313. break;
  314. // Movement
  315. case "^":
  316. this.MoveUp();
  317. break;
  318. case ">":
  319. this.MoveRight();
  320. break;
  321. case "v":
  322. this.MoveDown();
  323. break;
  324. case "<":
  325. this.MoveLeft();
  326. break;
  327. // Mirrors
  328. case "/":
  329. this.ReflectForward();
  330. break;
  331. case "\\":
  332. this.ReflectBack();
  333. break;
  334. case "_":
  335. this.VerticalMirror();
  336. break;
  337. case "|":
  338. this.HorizontalMirror();
  339. break;
  340. case "#":
  341. this.OmniMirror();
  342. break;
  343. // Trampolines
  344. case "!":
  345. this.Move();
  346. break;
  347. case "?":
  348. if(this.stacks[this.curr_stack].Pop() === 0){ this.Move(); }
  349. break;
  350. // Stack manipulation
  351. case "&": {
  352. if (this.stacks[this.curr_stack].register == null) {
  353. this.stacks[this.curr_stack].register = this.stacks[this.curr_stack].Pop();
  354. }
  355. else {
  356. this.stacks[this.curr_stack].Push(this.stacks[this.curr_stack].register);
  357. this.stacks[this.curr_stack].register = null;
  358. }
  359. break;
  360. }
  361. case ":":
  362. this.stacks[this.curr_stack].Duplicate();
  363. break;
  364. case "~":
  365. this.stacks[this.curr_stack].Remove();
  366. break;
  367. case "$":
  368. this.stacks[this.curr_stack].SwapTwo();
  369. break;
  370. case "@":
  371. this.stacks[this.curr_stack].SwapThree();
  372. break;
  373. case "{":
  374. this.stacks[this.curr_stack].ShiftLeft();
  375. break;
  376. case "}":
  377. this.stacks[this.curr_stack].ShiftRight();
  378. break;
  379. case "r":
  380. this.stacks[this.curr_stack].Reverse();
  381. break;
  382. case "l":
  383. this.stacks[this.curr_stack].PushLength();
  384. break;
  385. case "[": {
  386. this.SpliceStack(this.stacks[this.curr_stack].Pop());
  387. break;
  388. }
  389. case "]":
  390. this.CollapseStack();
  391. break;
  392. case "I": {
  393. this.curr_stack++;
  394. if (this.curr_stack >= this.stacks.length) {
  395. throw new RangeError("curr_stack value out of bounds");
  396. }
  397. break;
  398. }
  399. case "D": {
  400. this.curr_stack--;
  401. if (this.curr_stack < 0) {
  402. throw new RangeError("curr_stack value out of bounds");
  403. }
  404. break;
  405. }
  406. // Output
  407. case "n":
  408. output = this.stacks[this.curr_stack].Pop();
  409. break;
  410. case "o":
  411. output = String.fromCharCode(this.stacks[this.curr_stack].Pop());
  412. break;
  413. // Time
  414. case "S":
  415. setTimeout(this.Run.bind(this), this.stacks[this.curr_stack].Pop() * 100);
  416. this.Move();
  417. output = true;
  418. break;
  419. case "h":
  420. this.stacks[this.curr_stack].Push(this.datetime.getUTCHours());
  421. break;
  422. case "m":
  423. this.stacks[this.curr_stack].Push(this.datetime.getUTCMinutes());
  424. break;
  425. case "s":
  426. this.stacks[this.curr_stack].Push(this.datetime.getUTCSeconds());
  427. break;
  428. // Code box manipulation
  429. case "g":
  430. this.PushFromCodeBox();
  431. break;
  432. case "p":
  433. this.PlaceIntoCodeBox();
  434. break;
  435. // Functions
  436. case ".": {
  437. this.pointer.Y = this.stacks[this.curr_stack].Pop();
  438. this.pointer.X = this.stacks[this.curr_stack].Pop();
  439. break;
  440. }
  441. // End execution
  442. case ";":
  443. output = true;
  444. break;
  445. default:
  446. throw new Error(`Unknown instruction: ${instruction}`);
  447. }
  448. }
  449. catch(e) {
  450. console.error(`Something smells fishy!\n${e != "" ? `${e}\n` : ""}Instruction: ${instruction}\nStack: ${JSON.stringify(this.stacks[this.curr_stack].stack)}`);
  451. return true;
  452. }
  453. return output;
  454. }
  455. Swim() {
  456. if(this.debug.print.codeBox) { this.PrintCodeBox(); }
  457. if(this.debug.print.stacks) { this.PrintStacks(); }
  458. const instruction = this.box[this.pointer.Y][this.pointer.X];
  459. this.datetime = new Date();
  460. if(this.stringMode != 0 && dec(instruction) != this.stringMode) {
  461. this.stacks[this.curr_stack].Push(dec(instruction));
  462. }
  463. else {
  464. const exeResult = this.Execute(instruction);
  465. if(exeResult === true) {
  466. return true;
  467. }
  468. else if(exeResult != null) {
  469. this.Output(exeResult);
  470. }
  471. }
  472. this.Move();
  473. }
  474. Move() {
  475. let newX = this.pointer.X + this.curr_direction[0];
  476. let newY = this.pointer.Y + this.curr_direction[1];
  477. // Keep the X coord in the boxes bounds
  478. if(newX < 0) {
  479. newX = this.maxBoxWidth;
  480. }
  481. else if(newX > this.maxBoxWidth) {
  482. newX = 0;
  483. }
  484. // Keep the Y coord in the boxes bounds
  485. if(newY < 0) {
  486. newY = this.maxBoxHeight;
  487. }
  488. else if(newY > this.maxBoxHeight) {
  489. newY = 0;
  490. }
  491. this.SetPointer(newX, newY);
  492. }
  493. /**
  494. * Implement C and .
  495. */
  496. SetPointer(x, y) {
  497. this.pointer = {X: x, Y: y};
  498. }
  499. /**
  500. * Implement ^
  501. *
  502. * Changes the swim direction upward
  503. */
  504. MoveUp() {
  505. this.curr_direction = this.directions.NORTH;
  506. }
  507. /**
  508. * Implement >
  509. *
  510. * Changes the swim direction rightward
  511. */
  512. MoveRight() {
  513. this.curr_direction = this.directions.EAST;
  514. this.dirWasLeft = false;
  515. }
  516. /**
  517. * Implement v
  518. *
  519. * Changes the swim direction downward
  520. */
  521. MoveDown() {
  522. this.curr_direction = this.directions.SOUTH;
  523. }
  524. /**
  525. * Implement <
  526. *
  527. * Changes the swim direction leftward
  528. */
  529. MoveLeft() {
  530. this.curr_direction = this.directions.WEST;
  531. this.dirWasLeft = true;
  532. }
  533. /**
  534. * Implement /
  535. *
  536. * Reflects the swim direction depending on its starting value
  537. */
  538. ReflectForward() {
  539. if (this.curr_direction == this.directions.NORTH) {
  540. this.MoveRight();
  541. }
  542. else if (this.curr_direction == this.directions.EAST) {
  543. this.MoveUp();
  544. }
  545. else if (this.curr_direction == this.directions.SOUTH) {
  546. this.MoveLeft();
  547. }
  548. else {
  549. this.MoveDown();
  550. }
  551. }
  552. /**
  553. * Implement \
  554. *
  555. * Reflects the swim direction depending on its starting value
  556. */
  557. ReflectBack() {
  558. if (this.curr_direction == this.directions.NORTH) {
  559. this.MoveLeft();
  560. }
  561. else if (this.curr_direction == this.directions.EAST) {
  562. this.MoveDown();
  563. }
  564. else if (this.curr_direction == this.directions.SOUTH) {
  565. this.MoveRight();
  566. }
  567. else {
  568. this.MoveUp();
  569. }
  570. }
  571. /**
  572. * Implement |
  573. *
  574. * Swaps the horizontal swim direction to its opposite
  575. */
  576. HorizontalMirror() {
  577. if (this.curr_direction == this.directions.EAST) {
  578. this.MoveLeft();
  579. }
  580. else {
  581. this.MoveRight();
  582. }
  583. }
  584. /**
  585. * Implement _
  586. *
  587. * Swaps the horizontal swim direction to its opposite
  588. */
  589. VerticalMirror() {
  590. if (this.curr_direction == this.directions.NORTH) {
  591. this.MoveDown();
  592. }
  593. else {
  594. this.MoveUp();
  595. }
  596. }
  597. /**
  598. * Implement #
  599. *
  600. * A combination of the vertical and the horizontal mirror
  601. */
  602. OmniMirror() {
  603. if (this.curr_direction[0]) {
  604. this.VerticalMirror();
  605. }
  606. else {
  607. this.HorizontalMirror();
  608. }
  609. }
  610. /**
  611. * Implement x
  612. *
  613. * Pseudo-randomly switches the swim direction
  614. */
  615. ShuffleDirection() {
  616. this.curr_direction = Object.values(this.directions)[Math.floor(Math.random() * 4)];
  617. }
  618. /**
  619. * Implement [
  620. *
  621. * Takes X number of elements out of a stack and into a new stack
  622. *
  623. * This action creates a new stack, and places it on top of the one it was created from.
  624. * So, if you have three stacks, A, B, and C, and you splice a stack off of stack B,
  625. * the new order will be: A, B, D, and C.
  626. *
  627. * @see {@link https://esolangs.org/wiki/Fish#Stacks ><> Documentation}
  628. *
  629. * @param {int} spliceCount The number of elements to pop into a new stack
  630. */
  631. SpliceStack(spliceCount) {
  632. const stackCount = this.stacks[this.curr_stack].stack.length;
  633. if (spliceCount > stackCount) {
  634. throw new RangeError(`Cannot remove ${spliceCount} elements from a stack of only ${stackCount} elements`);
  635. }
  636. const newStack = new Stack(this.stacks[this.curr_stack].stack.splice(stackCount - spliceCount, spliceCount));
  637. // We're at the top of the stacks stack, so we can use .push
  638. if (this.curr_stack == this.stacks.length - 1) {
  639. this.stacks.push(newStack);
  640. }
  641. else {
  642. this.stacks.splice(this.curr_stack + 1, 0, newStack);
  643. }
  644. this.curr_stack++;
  645. }
  646. /**
  647. * Implement ]
  648. *
  649. * Collapses the current stack onto the one below it
  650. * If the current stack is the only one, it is replaced with a blank stack
  651. */
  652. CollapseStack() {
  653. // Undefined behavior collapsing the first stack down when there are other stacks available
  654. if (this.curr_stack == 0 && this.stacks.length != 1) {
  655. throw new Error();
  656. }
  657. if (this.curr_stack == 0) {
  658. this.stacks = [new Stack()];
  659. }
  660. else {
  661. const collapsed = this.stacks.splice(this.curr_stack, 1).pop();
  662. this.curr_stack--;
  663. const currStackCount = this.stacks[this.curr_stack].stack.length;
  664. this.stacks[this.curr_stack].stack.splice(currStackCount, 0, ...collapsed.stack);
  665. }
  666. }
  667. /**
  668. * Implement g
  669. *
  670. * Pops `y` and `x` from the stack, and then pushes the value of the character
  671. * at `[x, y]` in the code box.
  672. *
  673. * NOP's and coords that are out of bounds are converted to 0.
  674. *
  675. * Implements the behavior as defined by the original {@link https://gist.github.com/anonymous/6392418#file-fish-py-L306 ><>}, and not {@link https://github.com/redstarcoder/go-starfish/blob/master/starfish/starfish.go#L378 go-starfish}
  676. */
  677. PushFromCodeBox() {
  678. const y = this.stacks[this.curr_stack].Pop();
  679. const x = this.stacks[this.curr_stack].Pop();
  680. let val = undefined;
  681. try {
  682. val = this.box[y][x] || " ";
  683. }
  684. catch (e) {
  685. val = " ";
  686. }
  687. const valParsed = val == " " ? 0 : dec(val);
  688. this.stacks[this.curr_stack].Push(valParsed);
  689. }
  690. /**
  691. * Implement p
  692. *
  693. * Pops `y`, `x`, and `v` off of the stack, and then places the string
  694. * representation of that value at `[x, y]` in the code box.
  695. */
  696. PlaceIntoCodeBox() {
  697. const y = this.stacks[this.curr_stack].Pop();
  698. const x = this.stacks[this.curr_stack].Pop();
  699. const v = this.stacks[this.curr_stack].Pop();
  700. while(y >= this.box.length) {
  701. this.box.push([]);
  702. }
  703. while(x >= this.box[y].length) {
  704. this.box[y].push(" ");
  705. }
  706. this.EqualizeBoxWidth();
  707. this.box[y][x] = String.fromCharCode(v);
  708. }
  709. /**
  710. * Implement `
  711. *
  712. * Changes the swim direction based on the previous direction
  713. * @see https://esolangs.org/wiki/Starfish#Fisherman
  714. */
  715. Fisherman() {
  716. if (this.curr_direction[0]) {
  717. if (this.dirWasLeft) {
  718. this.MoveLeft();
  719. }
  720. else {
  721. this.MoveRight();
  722. }
  723. }
  724. else {
  725. if (this.onTheHook) {
  726. this.onTheHook = false;
  727. this.MoveUp();
  728. }
  729. else {
  730. this.onTheHook = true;
  731. this.MoveDown();
  732. }
  733. }
  734. }
  735. }
  736. /**
  737. * The stack class
  738. */
  739. class Stack {
  740. /**
  741. * @param {int[]} stackValues An array of values to initialize the stack with
  742. */
  743. constructor(stackValues = []) {
  744. /**
  745. * The stack
  746. * @type {int[]}
  747. */
  748. this.stack = stackValues;
  749. /**
  750. * A single value saved off the stack
  751. * @type {int}
  752. */
  753. this.register = null;
  754. }
  755. /**
  756. * Wrapper function for Array.prototype.push
  757. * @param {*} newValue
  758. */
  759. Push(newValue) {
  760. if(Array.isArray(newValue)) {
  761. this.stack.push(...newValue);
  762. }
  763. else {
  764. this.stack.push(newValue);
  765. }
  766. }
  767. /**
  768. * Wrapper function for Array.prototype.pop
  769. * @returns {*}
  770. */
  771. Pop() {
  772. const value = this.stack.pop();
  773. if(value == undefined){ throw new Error(); }
  774. return value;
  775. }
  776. /**
  777. * Implement }
  778. *
  779. * Shifts the entire stack leftward by one value
  780. */
  781. ShiftLeft() {
  782. const temp = this.stack.shift();
  783. this.stack.push(temp);
  784. }
  785. /**
  786. * Implement {
  787. *
  788. * Shifts the entire stack rightward by one value
  789. */
  790. ShiftRight() {
  791. const temp = this.stack.pop();
  792. this.stack.unshift(temp);
  793. }
  794. /**
  795. * Implement $
  796. *
  797. * Swaps the top two values of the stack
  798. */
  799. SwapTwo() {
  800. if(this.stack.length < 2) { throw new Error(); }
  801. const popped = this.stack.splice(this.stack.length - 2, 2);
  802. this.stack.push(...popped.reverse());
  803. }
  804. /**
  805. * Implement @
  806. *
  807. * Swaps the top three values of the stack
  808. */
  809. SwapThree() {
  810. if(this.stack.length < 3) { throw new Error(); }
  811. // Get the top three values
  812. const popped = this.stack.splice(this.stack.length - 3, 3);
  813. // Shift the elements to the right
  814. popped.unshift(popped.pop());
  815. this.stack.push(...popped);
  816. }
  817. /**
  818. * Implement :
  819. *
  820. * Duplicates the element on the top of the stack
  821. */
  822. Duplicate() {
  823. this.stack.push(this.stack[this.stack.length-1]);
  824. }
  825. /**
  826. * Implements ~
  827. *
  828. * Removes the element on the top of the stack
  829. */
  830. Remove() {
  831. this.stack.pop();
  832. }
  833. /**
  834. * Implement r
  835. *
  836. * Reverses the entire stack
  837. */
  838. Reverse() {
  839. this.stack.reverse();
  840. }
  841. /**
  842. * Implement l
  843. *
  844. * Pushes the length of the stack onto the top of the stack
  845. */
  846. PushLength() {
  847. this.stack.push(this.stack.length);
  848. }
  849. }
  850. /**
  851. * Get the char code of any character
  852. *
  853. * Can actually take any length of a value, but only returns the
  854. * char code of the first character.
  855. *
  856. * @param {*} value Any character
  857. * @returns {int} The value's char code
  858. */
  859. function dec(value) {
  860. return value.toString().charCodeAt(0);
  861. }