starfish.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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. // End execution
  436. case ";":
  437. output = true;
  438. break;
  439. default:
  440. throw new Error(`Unknown instruction: ${instruction}`);
  441. }
  442. }
  443. catch(e) {
  444. console.error(`Something smells fishy!\n${e != "" ? `${e}\n` : ""}Instruction: ${instruction}\nStack: ${JSON.stringify(this.stacks[this.curr_stack].stack)}`);
  445. return true;
  446. }
  447. return output;
  448. }
  449. Swim() {
  450. if(this.debug.print.codeBox) { this.PrintCodeBox(); }
  451. if(this.debug.print.stacks) { this.PrintStacks(); }
  452. const instruction = this.box[this.pointer.Y][this.pointer.X];
  453. this.datetime = new Date();
  454. if(this.stringMode != 0 && dec(instruction) != this.stringMode) {
  455. this.stacks[this.curr_stack].Push(dec(instruction));
  456. }
  457. else {
  458. const exeResult = this.Execute(instruction);
  459. if(exeResult === true) {
  460. return true;
  461. }
  462. else if(exeResult != null) {
  463. this.Output(exeResult);
  464. }
  465. }
  466. this.Move();
  467. }
  468. Move() {
  469. let newX = this.pointer.X + this.curr_direction[0];
  470. let newY = this.pointer.Y + this.curr_direction[1];
  471. // Keep the X coord in the boxes bounds
  472. if(newX < 0) {
  473. newX = this.maxBoxWidth;
  474. }
  475. else if(newX > this.maxBoxWidth) {
  476. newX = 0;
  477. }
  478. // Keep the Y coord in the boxes bounds
  479. if(newY < 0) {
  480. newY = this.maxBoxHeight;
  481. }
  482. else if(newY > this.maxBoxHeight) {
  483. newY = 0;
  484. }
  485. this.SetPointer(newX, newY);
  486. }
  487. /**
  488. * Implement C and .
  489. */
  490. SetPointer(x, y) {
  491. this.pointer = {X: x, Y: y};
  492. }
  493. /**
  494. * Implement ^
  495. *
  496. * Changes the swim direction upward
  497. */
  498. MoveUp() {
  499. this.curr_direction = this.directions.NORTH;
  500. }
  501. /**
  502. * Implement >
  503. *
  504. * Changes the swim direction rightward
  505. */
  506. MoveRight() {
  507. this.curr_direction = this.directions.EAST;
  508. this.dirWasLeft = false;
  509. }
  510. /**
  511. * Implement v
  512. *
  513. * Changes the swim direction downward
  514. */
  515. MoveDown() {
  516. this.curr_direction = this.directions.SOUTH;
  517. }
  518. /**
  519. * Implement <
  520. *
  521. * Changes the swim direction leftward
  522. */
  523. MoveLeft() {
  524. this.curr_direction = this.directions.WEST;
  525. this.dirWasLeft = true;
  526. }
  527. /**
  528. * Implement /
  529. *
  530. * Reflects the swim direction depending on its starting value
  531. */
  532. ReflectForward() {
  533. if (this.curr_direction == this.directions.NORTH) {
  534. this.MoveRight();
  535. }
  536. else if (this.curr_direction == this.directions.EAST) {
  537. this.MoveUp();
  538. }
  539. else if (this.curr_direction == this.directions.SOUTH) {
  540. this.MoveLeft();
  541. }
  542. else {
  543. this.MoveDown();
  544. }
  545. }
  546. /**
  547. * Implement \
  548. *
  549. * Reflects the swim direction depending on its starting value
  550. */
  551. ReflectBack() {
  552. if (this.curr_direction == this.directions.NORTH) {
  553. this.MoveLeft();
  554. }
  555. else if (this.curr_direction == this.directions.EAST) {
  556. this.MoveDown();
  557. }
  558. else if (this.curr_direction == this.directions.SOUTH) {
  559. this.MoveRight();
  560. }
  561. else {
  562. this.MoveUp();
  563. }
  564. }
  565. /**
  566. * Implement |
  567. *
  568. * Swaps the horizontal swim direction to its opposite
  569. */
  570. HorizontalMirror() {
  571. if (this.curr_direction == this.directions.EAST) {
  572. this.MoveLeft();
  573. }
  574. else {
  575. this.MoveRight();
  576. }
  577. }
  578. /**
  579. * Implement _
  580. *
  581. * Swaps the horizontal swim direction to its opposite
  582. */
  583. VerticalMirror() {
  584. if (this.curr_direction == this.directions.NORTH) {
  585. this.MoveDown();
  586. }
  587. else {
  588. this.MoveUp();
  589. }
  590. }
  591. /**
  592. * Implement #
  593. *
  594. * A combination of the vertical and the horizontal mirror
  595. */
  596. OmniMirror() {
  597. if (this.curr_direction[0]) {
  598. this.VerticalMirror();
  599. }
  600. else {
  601. this.HorizontalMirror();
  602. }
  603. }
  604. /**
  605. * Implement x
  606. *
  607. * Pseudo-randomly switches the swim direction
  608. */
  609. ShuffleDirection() {
  610. this.curr_direction = Object.values(this.directions)[Math.floor(Math.random() * 4)];
  611. }
  612. /**
  613. * Implement [
  614. *
  615. * Takes X number of elements out of a stack and into a new stack
  616. *
  617. * This action creates a new stack, and places it on top of the one it was created from.
  618. * So, if you have three stacks, A, B, and C, and you splice a stack off of stack B,
  619. * the new order will be: A, B, D, and C.
  620. *
  621. * @see {@link https://esolangs.org/wiki/Fish#Stacks ><> Documentation}
  622. *
  623. * @param {int} spliceCount The number of elements to pop into a new stack
  624. */
  625. SpliceStack(spliceCount) {
  626. const stackCount = this.stacks[this.curr_stack].stack.length;
  627. if (spliceCount > stackCount) {
  628. throw new RangeError(`Cannot remove ${spliceCount} elements from a stack of only ${stackCount} elements`);
  629. }
  630. const newStack = new Stack(this.stacks[this.curr_stack].stack.splice(stackCount - spliceCount, spliceCount));
  631. // We're at the top of the stacks stack, so we can use .push
  632. if (this.curr_stack == this.stacks.length - 1) {
  633. this.stacks.push(newStack);
  634. }
  635. else {
  636. this.stacks.splice(this.curr_stack + 1, 0, newStack);
  637. }
  638. this.curr_stack++;
  639. }
  640. /**
  641. * Implement ]
  642. *
  643. * Collapses the current stack onto the one below it
  644. * If the current stack is the only one, it is replaced with a blank stack
  645. */
  646. CollapseStack() {
  647. // Undefined behavior collapsing the first stack down when there are other stacks available
  648. if (this.curr_stack == 0 && this.stacks.length != 1) {
  649. throw new Error();
  650. }
  651. if (this.curr_stack == 0) {
  652. this.stacks = [new Stack()];
  653. }
  654. else {
  655. const collapsed = this.stacks.splice(this.curr_stack, 1).pop();
  656. this.curr_stack--;
  657. const currStackCount = this.stacks[this.curr_stack].stack.length;
  658. this.stacks[this.curr_stack].stack.splice(currStackCount, 0, ...collapsed.stack);
  659. }
  660. }
  661. /**
  662. * Implement g
  663. *
  664. * Pops `y` and `x` from the stack, and then pushes the value of the character
  665. * at `[x, y]` in the code box.
  666. *
  667. * NOP's and coords that are out of bounds are converted to 0.
  668. *
  669. * 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}
  670. */
  671. PushFromCodeBox() {
  672. const y = this.stacks[this.curr_stack].Pop();
  673. const x = this.stacks[this.curr_stack].Pop();
  674. let val = undefined;
  675. try {
  676. val = this.box[y][x] || " ";
  677. }
  678. catch (e) {
  679. val = " ";
  680. }
  681. const valParsed = val == " " ? 0 : dec(val);
  682. this.stacks[this.curr_stack].Push(valParsed);
  683. }
  684. /**
  685. * Implement p
  686. *
  687. * Pops `y`, `x`, and `v` off of the stack, and then places the string
  688. * representation of that value at `[x, y]` in the code box.
  689. */
  690. PlaceIntoCodeBox() {
  691. const y = this.stacks[this.curr_stack].Pop();
  692. const x = this.stacks[this.curr_stack].Pop();
  693. const v = this.stacks[this.curr_stack].Pop();
  694. while(y >= this.box.length) {
  695. this.box.push([]);
  696. }
  697. while(x >= this.box[y].length) {
  698. this.box[y].push(" ");
  699. }
  700. this.EqualizeBoxWidth();
  701. this.box[y][x] = String.fromCharCode(v);
  702. }
  703. /**
  704. * Implement `
  705. *
  706. * Changes the swim direction based on the previous direction
  707. * @see https://esolangs.org/wiki/Starfish#Fisherman
  708. */
  709. Fisherman() {
  710. if (this.curr_direction[0]) {
  711. if (this.dirWasLeft) {
  712. this.MoveLeft();
  713. }
  714. else {
  715. this.MoveRight();
  716. }
  717. }
  718. else {
  719. if (this.onTheHook) {
  720. this.onTheHook = false;
  721. this.MoveUp();
  722. }
  723. else {
  724. this.onTheHook = true;
  725. this.MoveDown();
  726. }
  727. }
  728. }
  729. }
  730. /**
  731. * The stack class
  732. */
  733. class Stack {
  734. /**
  735. * @param {int[]} stackValues An array of values to initialize the stack with
  736. */
  737. constructor(stackValues = []) {
  738. /**
  739. * The stack
  740. * @type {int[]}
  741. */
  742. this.stack = stackValues;
  743. /**
  744. * A single value saved off the stack
  745. * @type {int}
  746. */
  747. this.register = null;
  748. }
  749. /**
  750. * Wrapper function for Array.prototype.push
  751. * @param {*} newValue
  752. */
  753. Push(newValue) {
  754. if(Array.isArray(newValue)) {
  755. this.stack.push(...newValue);
  756. }
  757. else {
  758. this.stack.push(newValue);
  759. }
  760. }
  761. /**
  762. * Wrapper function for Array.prototype.pop
  763. * @returns {*}
  764. */
  765. Pop() {
  766. const value = this.stack.pop();
  767. if(value == undefined){ throw new Error(); }
  768. return value;
  769. }
  770. /**
  771. * Implement }
  772. *
  773. * Shifts the entire stack leftward by one value
  774. */
  775. ShiftLeft() {
  776. const temp = this.stack.shift();
  777. this.stack.push(temp);
  778. }
  779. /**
  780. * Implement {
  781. *
  782. * Shifts the entire stack rightward by one value
  783. */
  784. ShiftRight() {
  785. const temp = this.stack.pop();
  786. this.stack.unshift(temp);
  787. }
  788. /**
  789. * Implement $
  790. *
  791. * Swaps the top two values of the stack
  792. */
  793. SwapTwo() {
  794. if(this.stack.length < 2) { throw new Error(); }
  795. const popped = this.stack.splice(this.stack.length - 2, 2);
  796. this.stack.push(...popped.reverse());
  797. }
  798. /**
  799. * Implement @
  800. *
  801. * Swaps the top three values of the stack
  802. */
  803. SwapThree() {
  804. if(this.stack.length < 3) { throw new Error(); }
  805. // Get the top three values
  806. const popped = this.stack.splice(this.stack.length - 3, 3);
  807. // Shift the elements to the right
  808. popped.unshift(popped.pop());
  809. this.stack.push(...popped);
  810. }
  811. /**
  812. * Implement :
  813. *
  814. * Duplicates the element on the top of the stack
  815. */
  816. Duplicate() {
  817. this.stack.push(this.stack[this.stack.length-1]);
  818. }
  819. /**
  820. * Implements ~
  821. *
  822. * Removes the element on the top of the stack
  823. */
  824. Remove() {
  825. this.stack.pop();
  826. }
  827. /**
  828. * Implement r
  829. *
  830. * Reverses the entire stack
  831. */
  832. Reverse() {
  833. this.stack.reverse();
  834. }
  835. /**
  836. * Implement l
  837. *
  838. * Pushes the length of the stack onto the top of the stack
  839. */
  840. PushLength() {
  841. this.stack.push(this.stack.length);
  842. }
  843. }
  844. /**
  845. * Get the char code of any character
  846. *
  847. * Can actually take any length of a value, but only returns the
  848. * char code of the first character.
  849. *
  850. * @param {*} value Any character
  851. * @returns {int} The value's char code
  852. */
  853. function dec(value) {
  854. return value.toString().charCodeAt(0);
  855. }