function run (state) {
const {memory, pointer = 0, rbase = 0, input = [], outputs = [], halted = false} = state
let mem = memory.slice().split(",").map(Number)
const opcode = String(mem[pointer]).padStart(5,"0")
const command = +opcode.substring(3)
if(command===99 || pointer >= mem.length - 1)
return {memory: mem.join(","), pointer: pointer+2,
input: input.slice(1), outputs: outputs, rbase: rbase, halted: true}
let param1 = +opcode[2]===0 ? mem[mem[pointer+1]] :
+opcode[2]===1 ? mem[pointer+1] : mem[mem[pointer+1]+rbase],
param2 = +opcode[1]===0 ? mem[mem[pointer+2]] :
+opcode[1]===1 ? mem[pointer+2] : mem[mem[pointer+2]+rbase],
param3 = +opcode[0]===0 ? mem[pointer+3] : mem[pointer+3]+rbase
if(command===3) {
if(+opcode[2]==2) {
mem[param3] = input[0]
} else {
mem[mem[pointer+1]] = input[0]
}
return run({memory: mem.join(","),
pointer: pointer+2,
input: input.slice(1), outputs: outputs, rbase: rbase,
halted: halted})
}
if(command===4)
return run({memory: mem.join(","),
pointer: pointer+2,
input: input, outputs: outputs.concat(param1), rbase: rbase,
halted: halted})
if(command==5)
return run({memory: mem.join(","),
pointer: param1!=0 ? param2 : pointer+3,
input: input, outputs: outputs, rbase: rbase,
halted: halted})
if(command==6)
return run({memory: mem.join(","),
pointer: param1==0? param2 : pointer+3,
input: input, outputs: outputs, rbase: rbase,
halted: halted})
if(command==1) mem[param3] = param1 + param2
if(command==2) mem[param3] = param1 * param2
if(command==7) mem[param3] = param1 < param2 ? 1 : 0
if(command==8) mem[param3] = param1 == param2 ? 1 : 0
if(command==9)
return run({memory: mem.join(","),
pointer: pointer+2, rbase: rbase + param1,
input: input, outputs: outputs, halted: halted})
return run({memory: mem.join(","), pointer: pointer+4,
rbase: rbase, input: input, outputs: outputs, halted: halted})
}