-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtape_player.js
51 lines (40 loc) · 1.29 KB
/
tape_player.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
const access = require('./json_pointer');
const defaultTokenizer = require('./plain_text_delimiters')();
const defaultInstructionSet = require('./json_asm')(access)
module.exports = (tokenizer=defaultTokenizer, instructionSet=defaultInstructionSet) => {
const self = {
tokenizer,
instructionSet,
access,
statements: '__statements__', // Program
index: '__index__' // Program counter
};
self.play = (source, initial, done = () => {}) => {
initial[self.statements] = tokenizer.statements(source);
function next(finished) {
const command = tokenizer.command(initial[self.statements][initial[self.index]]);
if (!command) {
initial[self.index]++;
return next(finished);
};
if (!command.op) return done('Invalid command:' + JSON.stringify(command));
const wait = instructionSet[command.op](initial, ...command.args);
function go(inc) {
return function() {
if (inc) initial[self.index]++;
if (initial[self.index] >= initial[self.statements].length) return finished();
next(finished);
}
}
if (wait && typeof wait === 'number') return setTimeout(go(false), wait);
go(true)();
}
initial[self.index] = 0;
next(() => {
delete initial[self.statements];
delete initial[self.index];
done(null, initial);
});
};
return self;
};