-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy paththue-demo-6.js
58 lines (48 loc) · 1.35 KB
/
thue-demo-6.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
var fs = require('fs');
var shuffle = require('array-shuffle');
var prompt = require('sync-prompt').prompt;
function parse(str) {
var program = {
rules: [],
state: '',
exhausted: false
};
str = str.replace(/^(#::=.*)?$\n/mg, '');
var parts = str.split('\n::=\n');
program.state = parts[1];
program.rules = parts[0].split('\n').map(function(line) {
var index = line.indexOf('::=');
return [line.slice(0, index), line.slice(index + 3)];
});
return program;
}
function applyRule(state, rule) {
var rhs = rule[1];
if (rhs == ':::') {
rhs = prompt('Input: ');
} else if (rhs.match(/^~/)) {
var output = rhs.slice(1) || '\n';
process.stdout.write(output);
rhs = '';
}
return state.split(rule[0]).join(rhs);
}
function step(program) {
var rules = shuffle(program.rules);
program.exhausted = true;
for (var i = 0; i < rules.length; i++) {
if (program.state.indexOf(rules[i][0]) > -1) {
program.state = applyRule(program.state, rules[i]);
program.exhausted = false;
break;
}
}
return program;
}
function run(program) {
while (!program.exhausted) {
program = step(program);
}
}
var programString = fs.readFileSync(process.argv[2]).toString();
run(parse(programString));