-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode-eliminator.js
81 lines (67 loc) · 2.67 KB
/
code-eliminator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const fs = require('fs-extra'),
path = require('path'),
Confirm = require('prompt-confirm');
const esprima = require('esprima');
const escodegen = require('escodegen');
async function run(passedRunOptions) {
if (!passedRunOptions) {
console.log("Invalid Passed Arguemnts");
} else {
let modifiedCode = removeUnusedFunctions(passedRunOptions["inputFile"]);
console.log("Writting Modified Code:");
fs.writeFileSync(passedRunOptions["outputFile"], modifiedCode, "utf-8");
console.log("File Written");
}
}
function removeUnusedFunctions(inputFile) {
let code = fs.readFileSync(inputFile, "utf-8");
const ast = esprima.parseScript(code, { range: true, loc: true });
const declaredFunctions = {}
const calledFunctions = {};
function traverse(node) {
if (
(node.type === 'VariableDeclaration' && node.kind === 'const' && node.declarations.length === 1 &&
node.declarations[0].init && (node.declarations[0].init.type === 'ArrowFunctionExpression' || node.declarations[0].init.type === 'FunctionExpression'))
) {
if (node.declarations[0].id && node.declarations[0].id.type === 'Identifier') {
declaredFunctions[node.declarations[0].id.name] = true;
}
} else if(node.type == 'FunctionDeclaration') {
if (node.id && node.id.type === 'Identifier') {
declaredFunctions[node.id.name] = true;
}
} else if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
calledFunctions[node.callee.name] = true;
}
for (const key in node) {
if (node.hasOwnProperty(key)) {
const child = node[key];
if (typeof child === 'object' && child !== null) {
traverse(child);
}
}
}
}
traverse(ast);
const unusedArrowFunctions = Object.keys(declaredFunctions).filter(fun => !calledFunctions[fun]);
ast.body = ast.body.filter((node) => {
if (
node.type === 'VariableDeclaration' &&
node.kind === 'const' &&
node.declarations.length === 1 &&
node.declarations[0].init &&
(node.declarations[0].init.type === 'ArrowFunctionExpression' || node.declarations[0].init.type === 'FunctionExpression')
&& (unusedArrowFunctions.includes(node.declarations[0].id.name))) {
return false;
} else if(node.type == 'FunctionDeclaration' && node.id &&
(unusedArrowFunctions.includes(node.id.name))) {
return false;
}
return true;
});
const modifiedCode = escodegen.generate(ast);
return modifiedCode;
}
module.exports = {
run
}