The elf programmers are creating a small magical assembler to control the machines in Santa Claus's workshop.
To assist them, we will implement a simple interpreter that supports the following magical instructions:
MOV x y
: Copies the valuex
(which can be a number or the content of a register) into registery
.INC x
: Increments the content of registerx
by 1.DEC x
: Decrements the content of registerx
by 1.JMP x y
: If the value in registerx
is0
, then jumps to the instruction at indexy
and continues executing the program from there.
Expected behavior:
- If an attempt is made to access, increment, or decrement a register that has not been initialized, the default value
0
will be used. - The jump with
JMP
is absolute and goes to the exact index indicated byy
. - Upon completion, the program should return the content of register
A
. IfA
did not have a defined value, it returnsundefined
.
Note
Registers that have not been previously initialized are initialized to 0
.
const instructions = [
'MOV -1 C', // Copies -1 to register 'C'.
'INC C', // Increments the value of register 'C'.
'JMP C 1', // Jumps to the instruction at index 1 if 'C' is 0.
'MOV C A', // Copies register 'C' to register 'A'.
'INC A', // Increments the value of register 'A'.
]
compile(instructions) // Expected result: 2
/**
* Step-by-step execution:
* 0: "MOV -1 C" => The register C receives the value -1.
* 1: "INC C" => The register C becomes 0.
* 2: "JMP C 1" => C is 0, jumps to the instruction at index 1.
* 1: "INC C" => The register C becomes 1.
* 2: "JMP C 1" => C is 1, the instruction is ignored.
* 3: "MOV C A" => Copies register C to A. Now A is 1.
* 4: "INC A" => The register A becomes 2.
*/