I've been grappling with this challenge for a few days now. Essentially, what I'm trying to figure out is how to replicate this function as if it were coded in assembly language (or even machine code, using just one memory array), but executing everything within JavaScript?
function start() {
let x = doX(1, 2)
let y = doX(3, 4)
let z = doX(x, y)
return z
}
function doX(a, b) {
let x = a + b
let y = a - b
let z = x * y
return z
}
My attempt at solving it follows something like this:
const memory = []
function start() {
// emulate push operation (function prologue)?
memory[0] = 1
memory[1] = 2
doX()
memory[2] = memory[100]
memory[0] = 3
memory[1] = 4
doX()
memory[0] = memory[2]
memory[1] = memory[100]
doX()
// emulate pop operation (function epilogue)?
memory[100] = memory[100]
}
function doX() {
// find a way to reserve space "on the stack"
// by only using this memory object?
// Unsure of how to accomplish that....
memory[10] = memory[0] + memory[1]
memory[11] = memory[0] - memory[1]
memory[12] = memory[10] * memory[11]
// store result in return register?
memory[100] = memory[12]
}
How can I correctly implement the push and pop operations utilizing solely this memory array while ensuring it looks accurate? Also, I've hardwired all the memory addresses, so how can I make them relative appropriately?