Skip to content

Instantly share code, notes, and snippets.

@hzoo
Last active September 16, 2015 01:49
Show Gist options
  • Save hzoo/345e08d4456a8b63d06e to your computer and use it in GitHub Desktop.
Save hzoo/345e08d4456a8b63d06e to your computer and use it in GitHub Desktop.
babel formatter example - `add-curly`
// babel 5.8.22 with astexplorer.net
export default function ({ Plugin, types: t }) {
function addCurly(body) {
if (t.isExpressionStatement(body)) {
return t.blockStatement([body]);
} else if (Array.isArray(body) && body.length > 0 && !t.isBlockStatement(body[0])) {
return [t.blockStatement(body)];
} else {
return body;
}
}
return new Plugin("add-curly", {
visitor: {
IfStatement({ test, consequent, alternate }) {
consequent = addCurly(consequent);
alternate = addCurly(alternate);
if (alternate == null) {
return t.ifStatement(test, consequent);
} else {
return t.ifStatement(test, consequent, alternate);
}
},
WhileStatement({ test, body }) {
body = addCurly(body);
return t.WhileStatement(test, body);
},
ForStatement({ init, test, update, body }) {
body = addCurly(body);
return t.ForStatement(init, test, update, body);
},
ForInStatement({ left, right, body }) {
body = addCurly(body);
return t.ForInStatement(left, right, body);
},
ForOfStatement({ left, right, body }) {
body = addCurly(body);
return t.ForOfStatement(left, right, body);
},
DoWhileStatement({ body, test }) {
body = addCurly(body);
return t.DoWhileStatement(body, test);
},
SwitchCase({ consequent, test }) {
consequent = addCurly(consequent);
return t.SwitchCase(test, consequent);
}
}
});
}
if (x) x++, y++;
if (x) x++; else x--;
if (x) x++; else if (y) y++;
while (x) x--;
do x--; while (x);
for (var i = 0; i < 10; i++) x++;
for (x in x) x++;
for (x of y) x++;
switch (x) {
case 1:
case 2:
x++;
break;
case 3: {
x++;
break;
}
default:
x--;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment