jweinst1
5/6/2016 - 8:45 PM

sample, tiny virtual machine in javascript

sample, tiny virtual machine in javascript

//sample virtual machine in javascript

var VMJS = (function(){
	//object containing instructions for the VM
	var ASP = {
		"ins1":function(mach){
			mach.cells[mach.pointer] = 1;
		},
		"incp1":function(mach){
			mach.pointer += 1;
		}
	};
	function VMJS(){
		this.cells = [];
		this.pointer = 0;
		this.processor = ASP;
	}
	//executes a single instruction on the machine, causing state changes
	VMJS.prototype.instruct = function(code) {
		this.processor[code](this);
	};
	return VMJS;
})();

/*   var a = new VMJS();
   a
=> { cells: [], pointer: 0, processor: { ins1: [Function], incp1: [Function] } }
   a.instruct("ins1")
   a
=> { cells: [ 1 ], pointer: 0, processor: { ins1: [Function], incp1: [Function] } }
   a.instruct("incp1")
   a.instruct("ins1")
   a
=> { cells: [ 1, 1 ], pointer: 1, processor: { ins1: [Function], incp1: [Function] } }
   */