-
Notifications
You must be signed in to change notification settings - Fork 0
/
bf2.js
107 lines (105 loc) · 2.69 KB
/
bf2.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// v1.8
const settings = {
minus255ToPlus255: false, // whether the range should be -255 ~ 255 and not 0 ~ 255
windowsLineBreak: true // whether to use \r\n instead of \n
}
const fs = require("fs/promises");
var pr,
jspr = {
data: "",
tab: 0,
add: function(d){
this.data += d;
},
prev: "",
addline: function(d){
if(this.prev != d) {
let tabs = "";
if(this.tab > 0)for(let t=0;t<this.tab;t++)tabs+=" ";
this.data += (this.data.length==0?"":(settings.windowsLineBreak?"\r\n":"\n"))+tabs+d;
this.prev = d;
} else {
this.data += d;
}
}
},
arg = [...process.argv].splice(2);
async function main() {
if(!arg[0]) {
console.log('No file specified!');
process.exit(1);
return;
}
let filename = arg[0].toString().trim(),
filename2;
try {
filename2 = arg[1].toString().trim();
}catch(e){}
try {
if(filename2)console.log("Loading " + filename);
pr = await fs.readFile(filename,"utf8");
if(pr == '') throw new Error('The program is empty!');
} catch (e) {
console.error("Failed to load the program from a file. " + e);
process.exit(1);
return;
}
if(filename2)console.log("Converting...");
jspr.addline('let a=new Array(3e4),i=0,c=-1,p=[...process.argv].splice(2),w=v=>((v-'+'l)%(256-l)+(256-l))%(256-l)+l'.replaceAll('l',settings.minus255ToPlus255?'(-255)':'0')+';Object.seal&&(a.fill(0),Object.seal(a));');
let count = 0;
for(let i = 0; i < pr.length; i++) {
count = 0;
switch(pr[i]) {
case "+":
for(let o = 0; pr[i+o] == '+'; o++) {
count++;
}
i += count-1;
jspr.addline('a[i]=w(a[i]+'+count+');');
break;
case "-":
for(let o = 0; pr[i+o] == '-'; o++) {
count++;
}
i += count-1;
jspr.addline('a[i]=w(a[i]-'+count+');');
break;
case ">":
for(let o = 0; pr[i+o] == '>'; o++) {
count++;
}
i += count-1;
jspr.addline('i=Math.min(3e4,i+'+count+');');
break;
case "<":
for(let o = 0; pr[i+o] == '<'; o++) {
count++;
}
i += count-1;
jspr.addline('i=Math.max(0,i-'+count+');');
break;
case "[":
jspr.addline("for(;0!=a[i];) {");
jspr.tab++;
break;
case "]":
if(jspr.tab > 0) jspr.tab--;
jspr.addline("}");
break;
case ".":
jspr.addline('process.stdout.write(String.fromCharCode(a[i]));');
break;
case ",":
jspr.addline('c++,a[i]=p[0]?p[0].charCodeAt(c)?p[0].charCodeAt(c):0:0;');
break;
}
}
if(filename2) {
console.log("Conversion finished.");
await fs.writeFile(filename2,jspr.data);
console.log("Saved in " + filename2 + " (~" + Math.floor(jspr.data.length / 1024) + "kb of data)");
} else {
console.log(jspr.data);
}
}
main();