forked from kvbc/bf-ide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inp.js
87 lines (75 loc) · 2.16 KB
/
inp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
function Interpreter(mems) {
this.mem = new Array(mems).fill(0);
this.code = editor.getValue().BF();
this.mp = 0; // memory pointer
this.ip = 0; // instruction pointer
this.inpi = 0; // input iterator
this.start = new Map();
this.end = new Map();
}
Interpreter.prototype.data = function() {
return {
mem: this.mem,
code: this.code,
ip: this.ip,
mp: this.mp
};
},
Interpreter.prototype.eoc = function() {
return this.ip >= this.code.length;
}
Interpreter.prototype.init = function() {
let stack = [];
for(let i = 0; i < this.code.length; i++)
if(this.code[i] == '[') stack.push(i);
else if(this.code[i] == ']') {
let start = stack.pop();
this.start[i] = start;
this.end[start] = i;
}
}
Interpreter.prototype.step = function(by = 1) {
switch(this.code[this.ip]) {
case '>':
if(++this.mp >= this.mem.length)
this.mp = 0;
break;
case '<':
if(--this.mp < 0)
this.mp = this.mem.length - 1;
break;
case '+':
if(++this.mem[this.mp] > 255)
this.mem[this.mp] = 0;
break;
case '-':
if(--this.mem[this.mp] < 0)
this.mem[this.mp] = 255;
break;
case '.':
BF_INP.el.output.value += String.fromCharCode(this.mem[this.mp]);
break;
case ',':
const utf8EncodeText = new TextEncoder();
const byteArray = utf8EncodeText.encode(BF_INP.el.input.value);
if(this.inpi >= byteArray.length) break;
this.mem[this.mp] = byteArray[this.inpi++];
break;
case '[':
if(this.mem[this.mp] == 0)
this.ip = this.end[this.ip];
break;
case ']':
if(this.mem[this.mp] != 0)
this.ip = this.start[this.ip];
break;
}
this.ip += by;
}
Interpreter.prototype.skip = function() {
this.ip++;
}
Interpreter.prototype.run = function() {
while(this.ip < this.code.length)
this.step();
}