aboutsummaryrefslogtreecommitdiffstats
path: root/forth.js
diff options
context:
space:
mode:
authordan <[email protected]>2023-05-20 10:54:57 -0400
committerdan <[email protected]>2023-05-20 10:54:57 -0400
commit153cf4a4bab033bbb38341a01060ebbc60275132 (patch)
treefa195abcfad5fa4c6fd6a3daea62d1b881369175 /forth.js
parent84b064f65e25d6e6e3a8c8cfe8a10062a2da66a0 (diff)
downloadforth-153cf4a4bab033bbb38341a01060ebbc60275132.tar.gz
forth-153cf4a4bab033bbb38341a01060ebbc60275132.tar.bz2
forth-153cf4a4bab033bbb38341a01060ebbc60275132.zip
feat: `if` command; fix: input should be printed above output
Diffstat (limited to 'forth.js')
-rw-r--r--forth.js35
1 files changed, 27 insertions, 8 deletions
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 = `
<div id="forthouter">
<form id="forthform">
<label id="forthlinelabel" for="forthline" position="left">></label>
- <input id="forthline" type="text" value="">
+ <input id="forthline" type="text" value="" autocomplete="off">
</form>
<div id='forthresultsbox'>
<pre id="forthresults"></pre>
@@ -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;