forked from gabrielsroka/gabrielsroka.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpith.js
92 lines (84 loc) · 2.97 KB
/
pith.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
var tab = 2;
const get = fetch;
async function getJson(url, init) {
const r = await fetch(url, init);
return r.json();
}
document.querySelectorAll('script[type="text/pith"]').forEach(s => run(s.innerText));
function run(lines) {
lines = lines.split('\n');
var ind = 0;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
const tLine = line.trim();
if (tLine.startsWith('for ')) {
line = line
.replace('for', 'for (var')
.replace(' in ', ' of ');
line += ')';
} else if (tLine.startsWith('while ')) {
line = line.replace('while ', 'while (') + ')';
} else if (tLine.startsWith('def ') || tLine.startsWith('async def ')) {
if (line.endsWith(' main')) line = 'main()\n' + line;
line = line.replace('def', 'function');
if (!line.endsWith(')')) line += '()';
} else if (tLine.startsWith('if ') || tLine.startsWith('else if ') || tLine.startsWith('elif ')) {
line = line
.replace('elif', 'else if')
.replace('if ', 'if (')
.replace(' = ', ' == ');
line += ')';
} else if (tLine.startsWith('#')) {
line = line.replace('#', '//');
} else if (tLine.startsWith('print ') || tLine.startsWith('?')) {
line = line.replace(/(print|\?) ?/, 'print(') + ')';
} else if (tLine.startsWith('>')) {
line = line.replace('>', 'results.innerHTML +=') + ` + '<br>'`;
} else if (tLine.startsWith('|')) {
line = line.replace('|', 'table.tHead.innerHTML += `<tr><th>').replaceAll('|', '<th>') + '`';
} else if (tLine.startsWith('+')) {
line = line.replace('+', 'table.tBodies[0].innerHTML += `<tr><td>` + ').replaceAll('|', '+ `<td>` +').replaceAll('^', '+ `<td align=center>` +');
} else if (tLine.startsWith('tab = ')) {
eval(line);
line = '// ' + line;
}
var newInd = line.match(/^( *)/)[1].length / tab;
for (var t = newInd; t < ind; t++) {
line = ' '.repeat(tab * t) + '}\n' + line;
}
if (newInd > ind) lines[i - 1] += ' {';
ind = newInd;
lines[i] = line;
}
lines = '(async function () {\n' + lines.join('\n') + '\n}'.repeat(ind) + '\n})()';
console.log(lines);
eval(lines);
//document.body.appendChild(document.createElement("script")).innerHTML = lines;
}
function* range(start, stop, step = 1) {
if (stop == undefined) {
stop = start;
start = 0;
}
while (start < stop) {
yield start;
start += step;
}
}
function ac(it, cond, fn) {
return [...gen(it, cond, fn)];
}
function* gen(it, cond, fn) {
for (const n of it) {
if (cond == undefined || cond(n)) {
yield fn ? fn(n) : n;
}
}
}
function sum(it) {
var total = 0;
for (const n of it) {
total += n;
}
return total;
}