Created
September 9, 2008 17:26
-
-
Save monjudoh/9713 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Brainf**k in JavaScript1.6 | |
*/ | |
function Cell(memory){ | |
this._memory = memory || []; | |
if(!this._memory.length){ | |
this._memory.push(this); | |
} | |
}; | |
Cell.prototype._memory; | |
Cell.prototype._num = 0; | |
Cell.prototype.incr = function(){ | |
if(this._num < 255){ | |
this._num++; | |
} | |
return this; | |
}; | |
Cell.prototype.decr = function(){ | |
if(this._num > 0){ | |
this._num--; | |
} | |
return this; | |
}; | |
Cell.prototype.ptrIncr = function(){ | |
var mem = this._memory; | |
var idx = mem.indexOf(this); | |
if(idx < 0){ | |
throw new Error(); | |
}else if(idx < mem.length - 1){ | |
return mem[idx + 1]; | |
}else{ | |
var cell = new Cell(mem); | |
mem.push(cell); | |
return cell; | |
} | |
}; | |
Cell.prototype.ptrDecr = function(){ | |
var mem = this._memory; | |
var idx = this._memory.indexOf(this); | |
if(idx < 0){ | |
throw new Error(); | |
}else if(idx == 0){ | |
var cell = new Cell(mem); | |
mem.unshift(cell); | |
return cell; | |
}else{ | |
return mem[idx - 1]; | |
} | |
}; | |
Cell.prototype.put = function(){ | |
console.log(String.fromCharCode(this._num)); | |
} | |
Cell.prototype.getNum = function(){ | |
return this._num; | |
} | |
function fuck(source){ | |
var idx = 0; | |
var curr = new Cell(); | |
while(idx < source.length){ | |
switch(source.charAt(idx)){ | |
case '>': | |
curr = curr.ptrIncr(); | |
idx++; | |
break; | |
case '<': | |
curr = curr.ptrDecr(); | |
idx++; | |
break; | |
case '+': | |
curr.incr(); | |
idx++; | |
break; | |
case '-': | |
curr.decr(); | |
idx++; | |
break; | |
case ',': | |
idx++; | |
break; | |
case '.': | |
curr.put(); | |
idx++; | |
break; | |
case '[': | |
if(curr.getNum() == 0){ | |
var end = source.indexOf(']',idx); | |
if(end < 0){ | |
throw new Error(); | |
} | |
idx = end; | |
}else{ | |
idx++; | |
} | |
break; | |
case ']': | |
if(curr.getNum() != 0){ | |
var start = source.lastIndexOf('[',idx); | |
if(start < 0){ | |
throw new Error(); | |
} | |
idx = start; | |
}else{ | |
idx++; | |
} | |
break; | |
default: | |
throw new Error(); | |
} | |
} | |
} | |
/* | |
* HelloWorld | |
* fuck('+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+.'); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment