-
Notifications
You must be signed in to change notification settings - Fork 0
/
coprocessor.js
45 lines (35 loc) · 1.03 KB
/
coprocessor.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
const duet = (list) => {
const instructions = list
.split('\n')
.map((x) => x.trim().split(' '));
const registers = {};
let position = 0;
const getValue = (argument) => {
return isNaN(parseInt(argument))
? (registers[argument] || 0)
: parseInt(argument);
};
let numberOfTimesMulInvoked = 0;
while (position > -1 && position < instructions.length) {
const instruction = instructions[position];
const command = instruction[0];
const value1 = getValue(instruction[1]);
const value2 = getValue(instruction[2]);
if (command === 'set') {
registers[instruction[1]] = value2;
} else if (command === 'sub') {
registers[instruction[1]] = value1 - value2;
} else if (command === 'mul') {
registers[instruction[1]] = value1 * value2;
numberOfTimesMulInvoked++;
} else if (command === 'jnz') {
if (value1 !== 0) {
position += value2;
continue;
}
}
position++;
}
return numberOfTimesMulInvoked;
};
module.exports = duet;