Skip to content

Instantly share code, notes, and snippets.

@jaeschrich
Created June 15, 2013 14:05
Show Gist options
  • Save jaeschrich/5788258 to your computer and use it in GitHub Desktop.
Save jaeschrich/5788258 to your computer and use it in GitHub Desktop.
Syntax sugar javascript
/*
javascript syntax sugar
see comments for detials
*/
var vm = require("vm"),
fs = require("fs");
function compile(f){
fn = fs.readFileSync(f)
.toString()
// file << "Hi" -> file.write("Hi")
.replace(/\s+<<\s+([^\n|;]+)[\n|;]/g, ".write($1)")
/*
do, better for callbacks
fs.readFile("./stuff.json", do (err, dat) {
console.log(JSON.parse(dat.toString()));
});
->
fs.readFile("./stuff.json", function(err, dat) {
console.log(JSON.parse(dat.toString()));
});
var a = do {
alert("Hi!")
}
->
var a = function(){
alert("Hi")!
}
*/
.replace(/do[\s+]?(\([^\{]+\)[\s+]?)?\{([^\}]+)\}/g,
function (text, argList, body) {
if (!argList) {
return "function(){"+body+"}";
}
else {
return "function"+argList+"{"+body+"}";
}
})
/* def fn(){
alert("Hi!")
}
->
function fn(){
alert("Hi!")
}
*/
.split("def").join("function")
// print
.replace(/print\s+([^\n|;]+)/g, "console.log($1)")
// :: prototype shortcut
.replace(/\:\:/g, ".prototype.")
// :symbols
.replace(/\:([A-z-0-9]+)/g, '"$1"')
// import http -> var http = require("http");
.replace(/import\s+([^\s|\n|;]+)/g, 'var $1 = require("$1");')
// @val -> this.val
.replace(/\@/g, "this.")
// write code to stdout
console.log(fn);
}
exports.compile = compile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment