Skip to content

Instantly share code, notes, and snippets.

@psema4
Last active August 29, 2015 14:09
Show Gist options
  • Save psema4/eddb24f3adb98d53d436 to your computer and use it in GitHub Desktop.
Save psema4/eddb24f3adb98d53d436 to your computer and use it in GitHub Desktop.
Barebones "One-Instruction Set Computer" in a web page
<!doctype html>
<html lang="en">
<head>
<title>OISC in a web page</title>
</head>
<body>
<script>
/* pseudocode source: http://en.wikipedia.org/wiki/One_instruction_set_computer
integer memory[], program_counter, a, b, c
program_counter = 0
while (program_counter >= 0):
a = memory[program_counter]
b = memory[program_counter+1]
c = memory[program_counter+2]
if (a < 0 or b < 0):
program_counter = -1
else:
memory[b] = memory[b] - memory[a]
if (memory[b] > 0):
program_counter = program_counter + 3
else:
program_counter = c
*/
window.addEventListener('load', function() {
console.log('load');
var memory, pc, a, b, c;
pc = 0; // program counter
memory = [ // Addr Instr
0, 0, 9 // 0 - JMP 9
, -1, -1, -1 // 3 - HALT
, -1, -1, -1 // 6 - HALT
, -1, -1, -1 // 9 - HALT
, -1. -1. -1 // 12 - HALT
];
do {
a = memory[pc];
b = memory[pc+1];
c = memory[pc+2];
// dump registers
console.log("PC:%s A:%s B:%s C:%s", pc, a, b, c);
if ((a < 0) || (b < 0)) {
pc = -1; // stop program
} else {
// subtract and branch if less than or equal to zero
memory[b] = memory[b] - memory[a];
if (memory[b] > 0) {
pc = pc + 3; // read next instruction
} else {
pc = c; // set pc
}
}
} while (pc >= 0);
console.log('halt');
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment