UNPKG

2.65 kBJavaScriptView Raw
1var esprima = require('esprima');
2var escodegen = require('escodegen');
3
4
5module.exports = function (func) {
6 var ast = esprima.parse(func);
7
8 var funcRoot = ast.body[0].body.body;
9 if (funcRoot.length === 5) {
10 // determine if there are only the buf declaration, the push of one string and then the return of the buf.join
11 var simpleString = '';
12 var cnt = 0;
13
14 funcRoot.forEach(function (node, i) {
15 // check for buf declare
16 if (i === 0 && node.type === "VariableDeclaration" && node.declarations[0].id.name === "buf" &&
17 (node.declarations[0].init.elements instanceof Array && node.declarations[0].init.elements.length === 0)) {
18 cnt++;
19 }
20
21 // check for jade_mixins declare
22 if (i === 1 && node.type === "VariableDeclaration" && node.declarations[0].id.name === "jade_mixins" &&
23 (node.declarations[0].init.type === 'ObjectExpression' && node.declarations[0].init.properties.length === 0)) {
24 cnt++;
25 }
26
27 // check for jade_interp declare
28 if (i === 2 && node.type === "VariableDeclaration" && node.declarations[0].id.name === "jade_interp" &&
29 (node.declarations[0].init === null)) {
30 cnt++;
31 }
32
33 // check for single string push
34 if (i === 3 && node.type === "ExpressionStatement" && node.expression.callee && node.expression.callee.object.name === "buf" &&
35 node.expression.arguments.length === 1 && node.expression.arguments[0].type === "Literal") {
36 // save the simple string
37 simpleString = node.expression.arguments[0].value;
38 cnt++;
39 }
40
41 // check for buf join
42 if (i === 4 && node.type === "ReturnStatement" && node.argument.callee.object.name === "buf" &&
43 node.argument.callee.property.name === "join" && node.argument.arguments.length === 1 && node.argument.arguments[0].value === '') {
44 cnt++;
45 }
46 });
47
48 // All the conditions were met, it's a simple template
49 if (cnt === 5) {
50 // replace the funcRoot with a simple return;
51 var simpleRoot = [{
52 type: 'ReturnStatement',
53 argument: {
54 type: 'Literal',
55 value: simpleString
56 }
57 }];
58 ast.body[0].body.body = simpleRoot;
59
60 //remove function parameter
61 ast.body[0].params = [];
62 }
63 }
64
65 return escodegen.generate(ast);
66};
\No newline at end of file