-
Notifications
You must be signed in to change notification settings - Fork 0
/
js-dcc-multi-functions.js
51 lines (46 loc) · 1.49 KB
/
js-dcc-multi-functions.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
let bfCode = null;
const output = (c) => {
postMessage(c)
};
const compose = (bfCode) => {
let funcCounter = 0;
let p = 0;
const funcBodyList = [];
const builder = () => {
const funcId = funcCounter++;
let funcBody = `function func${funcId}() {`;
while(p < bfCode.length) {
const c = bfCode[p++];
switch (c) {
case '>': funcBody += 'pointer++;'; break;
case '<': funcBody += 'pointer--;'; break;
case '+': funcBody += 'memory[pointer]++;'; break;
case '-': funcBody += 'memory[pointer]--;'; break;
case '.': funcBody += `output(memory[pointer]);`; break;
case '[':
funcBody += `while (memory[pointer]) {`;
const calleeId = builder();
funcBody += `func${calleeId}();`;
funcBody += `}`;
break;
case ']':
funcBody += `}`;
funcBodyList.push(funcBody);
return funcId;
}
}
funcBody += `}`;
funcBodyList.push(funcBody);
return funcId;
};
builder();
let rootBody = `let pointer = 0;const memory = new Int32Array(30000);`;
rootBody += funcBodyList.join('');
rootBody += 'func0();output(null);'
return new Function(rootBody);
};
onmessage = (e) => {
bfCode = e.data;
const compute = compose(bfCode);
compute();
};