Saturday, May 1, 2010

Self replicating JavaScript

Running the following programm with node.js will produce the exact output that makes up the program.

#!/usr/bin/env node

var sys = require("sys");

var repl = function () {

    sys.puts("#!/usr/bin/env node\n\nvar sys = require(\"sys\");\n\nvar repl = " + repl + "\n\nrepl();");


Assuming you put the code in the file replicate.js you should be able to do the following (on unix):
node replicate.js > r2.js
diff replicate.js r2.js && echo same
node r2.js > r3.js
diff r2.js r3.js && echo sameThis code was inspired by