-
Notifications
You must be signed in to change notification settings - Fork 1
/
interpreter.js
71 lines (57 loc) · 1.45 KB
/
interpreter.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
module.exports = function (tokens, state) {
const length = tokens.length;
let i = 0;
while (i < length) {
const { pointer, tape, } = state;
const bite = tape[pointer];
const { character, end, line, start, type, } = tokens[i];
if (type === '[') {
if (bite) {
++i;
continue;
} else {
i = end + 1;
continue;
}
}
if (type === ']') {
if (bite) {
i = start + 1;
continue;
} else {
++i;
continue;
}
}
if (type === '+') {
const nextBite = (tape[pointer] || 0) + 1;
state.tape[pointer] = nextBite > 255 ? 0 : nextBite;
}
if (type === '-') {
const nextBite = (tape[pointer] || 0) - 1;
state.tape[pointer] = nextBite < 0 ? 255 : nextBite;
}
if (type === '<') {
--state.pointer;
if (state.pointer !== state.pointer || state.pointer < 0) {
throw new RangeError(
`Your program used the < command one too many times in a row.
You are already at the left-most memory position.
Check line ${line}, character ${character}.`
);
}
}
if (type === '>') {
++state.pointer;
}
if (type === ',') {
state.tape[pointer] = state.input.charCodeAt() || 0;
state.input = state.input.substring(1);
}
if (type === '.') {
state.output += String.fromCharCode(tape[pointer]);
}
++i;
}
return state;
};