Nobody writes hex by hand
Wasm has a text format (WAT). Write a small assembler for its instructions — look each one up in an opcode table and encode its argument as LEB128 — then use it to program a loop with block, loop and br_if.
Structured control flow
const FACT_TEXT = `
i32.const 1 local.set 1 ;; acc = 1
block
loop
local.get 0 i32.const 1 i32.le_s br_if 1 ;; if n <= 1: leave the block
local.get 1 local.get 0 i32.mul local.set 1 ;; acc = acc * n
local.get 0 i32.const 1 i32.sub local.set 0 ;; n = n - 1
br 0 ;; back to the loop
end
end
local.get 1`;Wasm has no goto: only branches to enclosing blocks and loops, which keeps it easy to validate and compile.