@@ -10,32 +10,33 @@ const multiply = ({ posIn1, posIn2, posOut, data }) => {
1010 return true
1111}
1212
13- const terminate = ( { position } ) => {
14- console . log ( `Reached terminator at position ${ position } . Stopping.` )
13+ const terminate = ( { instructionPointer } ) => {
14+ console . log ( `Reached terminator at instructionPointer ${ instructionPointer } . Stopping.` )
1515 return false
1616}
1717
18- const step = ( { position , data } ) => {
19- console . debug ( `Step: ${ position } ` )
18+ const step = ( { instructionPointer , data } ) => {
19+ console . debug ( `Step: ${ instructionPointer } ` )
2020 const opCodesMap = {
2121 1 : add ,
2222 2 : multiply ,
2323 99 : terminate
2424 }
25- const segment = data . slice ( position , position + 4 )
25+ const instruction = data . slice ( instructionPointer , instructionPointer + 4 )
26+ const opcode = instruction [ 0 ]
2627
2728 // Run the correct opcode for the specified step
28- return opCodesMap [ data [ position ] ] ( {
29- posIn1 : segment [ 1 ] ,
30- posIn2 : segment [ 2 ] ,
31- posOut : segment [ 3 ] ,
29+ return opCodesMap [ opcode ] ( {
30+ posIn1 : instruction [ 1 ] ,
31+ posIn2 : instruction [ 2 ] ,
32+ posOut : instruction [ 3 ] ,
3233 data,
33- position
34+ instructionPointer
3435 } )
3536}
3637
3738const runProgram = ( { data } ) => {
38- let position = 0
39+ let instructionPointer = 0
3940 let running = true
4041
4142 // Convert to BigInts because operations will exceed 53bit integers
@@ -45,9 +46,10 @@ const runProgram = ({ data }) => {
4546 // eslint-disable-next-line no-undef
4647 data . forEach ( ( key , idx ) => { data [ idx ] = BigInt ( key ) } )
4748
48- while ( running === true && position <= data . length ) {
49- running = step ( { position, data } )
50- position += 4
49+ while ( running === true && instructionPointer <= data . length ) {
50+ const instructionLength = 4
51+ running = step ( { instructionPointer, data } )
52+ instructionPointer += instructionLength
5153 }
5254}
5355
0 commit comments