forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvarify.js
More file actions
24 lines (21 loc) · 717 Bytes
/
varify.js
File metadata and controls
24 lines (21 loc) · 717 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let {parse} = require("acorn")
module.exports = function(code) {
let ast
try { ast = parse(code) }
catch(_) { return code }
let patches = []
ast.body.forEach(node => {
if (node.type == "VariableDeclaration" && node.kind != "var")
patches.push({from: node.start, to: node.start + node.kind.length, text: "var"})
if (node.type == "ClassDeclaration")
patches.push({from: node.start, to: node.start, text: "var " + node.id.name + " = "})
})
patches.sort((a, b) => a.from - b.from || (a.to || a.from) - (b.to || b.from))
let out = "", pos = 0
patches.forEach(({from, to, text}) => {
out += code.slice(pos, from) + text
pos = to
})
out += code.slice(pos)
return out
}