Initial scripts for javascript impl of brainmess javaGoofing
authorMichael Welch <michaelgwelch@gmail.com>
Tue, 13 Mar 2012 14:34:49 +0000 (09:34 -0500)
committerMichael Welch <michaelgwelch@gmail.com>
Tue, 13 Mar 2012 14:34:49 +0000 (09:34 -0500)
js/context.js [new file with mode: 0644]
js/tape.js [new file with mode: 0644]

diff --git a/js/context.js b/js/context.js
new file mode 100644 (file)
index 0000000..ea186b4
--- /dev/null
@@ -0,0 +1,21 @@
+var Context = function() {
+    return {
+        forward: function(prog, tape, input, output) { tape.forward(); },
+        backward: function(prog, tape, input, output) { tape.backward(); },
+        inc: function(prog, tape, input, output) { tape.inc(); },
+        dec: function(prog, tape, input, output) { tape.dec(); },
+        testAndJumpForward: function(prog, tape, input, output) {
+            if (tape.get() === 0) prog.jumpForward();
+        },
+        testAndJumpBackward: function(prog, tape, input, output) {
+            if (tape.get() !== 0) prog.jumpBackward();
+        },
+        input: function(prog, tape, input, output) { 
+            tape.set(input());
+        },
+        output: function(prog, tape, input, output) {
+            output(tape.get());
+        }
+    };
+}
+
diff --git a/js/tape.js b/js/tape.js
new file mode 100644 (file)
index 0000000..3ec1158
--- /dev/null
@@ -0,0 +1,30 @@
+var Tape = function() {
+    var cells = [0];
+    var index = 0;
+
+    return {
+        inc: function() { cells[index]++; },
+        dec: function() { cells[index]--; },
+        forward: function() { 
+            index++;
+            if (index === cells.length) cells.push(0);
+        },
+        backward: function() { 
+            if (index > 0) index--;
+            else cells.unshift(0);
+        },
+        get: function() { return cells[index]; },
+        set: function(v) { cells[index] = v; },
+        toString: function() { 
+            var result = "";
+            var i = 0;
+            for(i = 0; i < cells.length; i++) {
+                if (i !== 0) result += ",";
+                if (i === index) result += "->";
+                result += cells[i].toString();
+            }
+            return result;
+        },
+        index: function() { return index; }
+    }
+};