-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (81 loc) · 2.73 KB
/
index.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
93
94
95
96
97
98
99
100
101
102
103
104
/**
* @param {string[]} commands
* @returns {number[]}
*/
function executeCommands(commands) {
const registers = [0, 0, 0, 0, 0, 0, 0, 0]
let commandIndex = 0
const ACTIONS = {
ADD: ([index1, index2]) =>
(registers[index1] = fixNumber(registers[index1] + registers[index2])),
CPY: ([sourceIndex, destinationIndex]) =>
(registers[destinationIndex] = registers[sourceIndex]),
DEC: ([index]) => (registers[index] = fixNumber(registers[index] - 1)),
INC: ([index]) => (registers[index] = fixNumber(registers[index] + 1)),
JMP: ([index]) => registers[0] !== 0 && (commandIndex = index - 1),
MOV: ([value, index]) => (registers[index] = value),
}
const fixNumber = number => (number + 256) % 256
const parseCommand = command => {
let [action, args] = command.split(' ')
if (action === 'MOV' && args[0] === 'V') action = 'CPY'
args = args.split(',').map(arg => Number(arg.replace('V', '')))
return {action, args}
}
const parsedCommands = commands.map(parseCommand)
while (commandIndex < parsedCommands.length) {
const parsedCommand = parsedCommands[commandIndex]
ACTIONS[parsedCommand.action](parsedCommand.args)
commandIndex++
}
return registers
}
/**
* Optimized version to get a higher score but less readable and maintainable
*
* @param {string[]} commands
* @returns {number[]}
*/
function executeCommandsOptimized(commands) {
const registers = [0, 0, 0, 0, 0, 0, 0, 0]
let commandIndex = 0
const ACTIONS = {
ADD: args => {
const [index1, index2] = args
.split(',')
.map(index => Number(index.slice(1)))
registers[index1] = fixNumber(registers[index1] + registers[index2])
},
DEC: index => {
index = Number(index.slice(1))
registers[index] = fixNumber(registers[index] - 1)
},
INC: index => {
index = Number(index.slice(1))
registers[index] = fixNumber(registers[index] + 1)
},
JMP: index => {
const shouldJump = !!registers[0]
commandIndex =
Number(shouldJump) * (index - 1) + Number(!shouldJump) * commandIndex
},
MOV: args => {
let [value, index] = args.split(',')
index = Number(index.slice(1))
const shouldCopyRegister = value.startsWith('V')
value =
Number(shouldCopyRegister) *
registers[Number(shouldCopyRegister) * Number(value.slice(1))] +
Number(!shouldCopyRegister) * ~~Number(value)
registers[index] = value
},
}
const fixNumber = number => (number + 256) % 256
while (commandIndex < commands.length) {
const [action, args] = commands[commandIndex].split(' ')
ACTIONS[action](args)
commandIndex++
}
return registers
}
export {executeCommands, executeCommandsOptimized}