From 153cf4a4bab033bbb38341a01060ebbc60275132 Mon Sep 17 00:00:00 2001 From: dan Date: Sat, 20 May 2023 10:54:57 -0400 Subject: feat: `if` command; fix: input should be printed above output --- forth.js | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) (limited to 'forth.js') diff --git a/forth.js b/forth.js index ab3dba6..54b9d1d 100644 --- a/forth.js +++ b/forth.js @@ -3,9 +3,6 @@ function forth(print = console.log) { const popNum = () => Number(s.pop()); const fs = { - ' ' : () => {}, - '\n' : () => {}, - '\t' : () => {}, '/' : () => { const a2 = popNum(); const a1 = popNum(); @@ -18,6 +15,16 @@ function forth(print = console.log) { }, '+' : () => { s.push(popNum() + popNum()) }, '*' : () => { s.push(popNum() * popNum()) }, + '=' : () => { s.push(popNum() === popNum()) }, + 'then' : () => {/*Doing nothing skips the token*/}, + 'if' : (initialIdx, tokens) => { + if (!s.pop()) { + let localIdx = initialIdx; + while (tokens[localIdx] && tokens[localIdx] !== 'then') {localIdx++} + return localIdx - initialIdx; + } + }, + 'not' : () => { s.push(!s.pop()) }, '.' : () => { print(s.pop()) }, 'peek' : () => { print(s[s.length - 1]) }, 'dup' : () => { s.push(s[s.length - 1]) }, @@ -62,7 +69,13 @@ function forth(print = console.log) { } } } - return t => exec(t.split(/[ \n\t]+/)); + return t => + new Promise( + resolve => { + exec(t.split(/[ \n\t]+/).filter(x => x !== '')); + resolve(); + } + ); } /* @@ -96,19 +109,25 @@ if (typeof window !== 'undefined') { // browser UI height: 90vh; } #forthresults { + height: 100%; margin-top: 0px; + overflow: clip; + margin: 0px; } #forthlinelabel { padding-top:1px; max-width: 3%; } + #forthform { + margin-bottom: 0px; + } `; document.head.appendChild(style); forthroot.innerHTML = `
- +

@@ -118,9 +137,9 @@ if (typeof window !== 'undefined') { // browser UI
   const print = x => { forthresults.innerHTML = x + '\n' + forthresults.innerHTML; };
   const m = forth(print);
   forthform.onsubmit = () => {
-    print(`> ${forthline.value}`);
-    if (forthline.value !== '') {
-      m(forthline.value);
+    const input = forthline.value;
+    if (input !== '') {
+      m(input).then(() => print(`> ${input}`));
       forthline.value = '';
     }
     return false;
-- 
cgit v1.2.3