implement constants

This commit is contained in:
Sebastian McKenzie
2014-09-29 12:24:21 +10:00
parent 886ed42b78
commit 74f831bd39
3 changed files with 57 additions and 10 deletions

View File

@@ -9,20 +9,26 @@ var isLet = function (node) {
}
};
var hasLet = function (nodes) {
var has = false;
_.each(nodes, function (node) {
if (isLet(node)) has = true;
});
return has;
};
exports.Program = function (node) {
_.each(node.body, isLet);
if (hasLet(node.body)) {
node.body = [buildNode(node.body)];
}
};
exports.BlockStatement = function (node, parent) {
var hasLet = false;
if (!hasLet(node.body)) return;
_.each(node.body, function (bodyNode) {
if (isLet(bodyNode)) hasLet = true;
});
if (!hasLet) return;
// ignore if we're direct children of a closure already
// ignore if we're the body of a closure already
if (parent.type === "FunctionExpression") return;
node.body = [buildNode(node.body)];

View File

@@ -0,0 +1,41 @@
var traverse = require("../traverse");
var util = require("../util");
var _ = require("lodash");
exports.Program =
exports.BlockStatement =
exports.ForInStatement =
exports.ForStatement = function (node) {
var constants = [];
var check = function (node, name) {
if (constants.indexOf(name) >= 0) {
throw util.errorWithNode(node, name + " is read-only");
}
};
_.each(node.body, function (child) {
if (child.type === "VariableDeclaration" && child.kind === "const") {
_.each(child.declarations, function (declar) {
var name = declar.id.name;
check(declar, name);
declar._ignoreConstant = true;
constants.push(name);
});
child.kind = "let";
}
});
if (!constants.length) return;
traverse(node, function (child) {
if (child._ignoreConstant) return;
if (child.type === "VariableDeclarator") {
check(child, child.id.name);
} else if (child.type === "AssignmentExpression") {
check(child, child.left.name);
}
});
};