-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathprogram.js
More file actions
76 lines (63 loc) · 1.68 KB
/
program.js
File metadata and controls
76 lines (63 loc) · 1.68 KB
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
// Helper, I use this a bit
const isStr = val => typeof val === 'string';
const default_registers = {
a: 0,
b: 0,
c: 0,
d: 0,
e: 0,
f: 0,
g: 0,
h: 0,
};
class Program {
constructor(program, registers = default_registers) {
this.program = JSON.parse(JSON.stringify(program));
this.registers = registers;
this.index = 0;
this.finished = false;
this.mul_instruction_count = 0;
}
set(register, value) {
this.registers[register] = this.getValueAtRegister(value);
}
sub(register, value) {
this.registers[register] -= this.getValueAtRegister(value);
}
mul(register, value) {
this.mul_instruction_count++;
this.registers[register] *= this.getValueAtRegister(value);
}
jnz(value, offset) {
if (this.getValueAtRegister(value) !== 0) {
this.index += this.getValueAtRegister(offset);
return true;
} else {
return false;
}
}
getValueAtRegister(value) {
return isStr(value) ? this.registers[value] : value;
}
tick() {
let { type, x, y } = this.program[this.index] || {};
if (!type) return false;
let value = this[type](x, y);
if (type === 'jnz' && value === true) {
// Do nothing, we jumped. Otherwise, skip the `jnz` instruction
} else {
this.index++;
}
return true;
}
run() {
while (this.tick()) {
// Do nothing...
}
return this.mul_instruction_count;
}
peekCurrentInstructionType() {
return this.program[this.index].type;
}
}
module.exports = Program;