From a2b4d6e4add48ce587cc95c0405e1a780240c71c Mon Sep 17 00:00:00 2001 From: n loewen Date: Tue, 25 Jul 2023 19:03:47 +0100 Subject: [PATCH] After running, print a snapshot of memory as it was before running, as well as a snapshot of the final memory state. Also: refactor `log_memory()` into a more generic `log_table_with_title()` --- simulator-sketch.js | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/simulator-sketch.js b/simulator-sketch.js index 84b1c26..34d83c4 100644 --- a/simulator-sketch.js +++ b/simulator-sketch.js @@ -24,14 +24,14 @@ function CPU(mem) { store_lit: (lit) => { console.log('STO lit#'); this.memory[lit] = this.acc; - log_memory(); + log_table_with_title(this.memory, 'Current memory'); this.instructionPointer = this.instructionPointer += 1; }, store_addr: (addr) => { console.log('STO addr'); this.memory[this.memory[addr]] = this.acc; - log_memory(); + log_table_with_title(this.memory, 'Memory'); this.instructionPointer = this.instructionPointer += 1; }, @@ -51,7 +51,7 @@ function CPU(mem) { add_lit: (lit) => { console.log("ADD lit"); if ( (this.acc + lit) > 15 ) { this.carryFlag = 1; } - this.acc = (this.acc + lit % 15); + this.acc = ((this.acc + lit) % 15); this.instructionPointer = this.instructionPointer += 1; }, @@ -172,7 +172,7 @@ function CPU(mem) { case 12: this.instructions.jump_addr(arg); break; - + case 13: this.instructions.carry_clear(arg); break; @@ -187,6 +187,7 @@ function CPU(mem) { } this.run_program = () => { + const initialMemory = JSON.parse(JSON.stringify(this.memory)); // Hack to make a copy-by-value -- https://stackoverflow.com/questions/18829099/copy-a-variables-value-into-another console.log(); console.log("————————————————————————————————————————"); let time = new Date(); @@ -208,6 +209,11 @@ function CPU(mem) { console.groupEnd("Processing instruction"); } } + + return { + memoryAtStart: initialMemory, + memoryAtEnd: this.memory + } } log_debug_state = () => { @@ -217,13 +223,13 @@ function CPU(mem) { console.log(); console.groupEnd('CPU state'); }; +}; - log_memory = () => { - console.log(); - console.group('Memory'); - console.table(this.memory); - console.groupEnd('Memory'); - }; +log_table_with_title = (memory, tableTitle) => { + console.log(); + console.group(tableTitle); + console.table(memory); + console.groupEnd(tableTitle); };