UNPKG

tslint-immutable

Version:

TSLint rules to disable mutation in TypeScript.

63 lines 3.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ts = require("typescript"); var Lint = require("tslint"); var utils = require("tsutils/typeguard/2.8"); var Ignore = require("./shared/ignore"); var check_node_1 = require("./shared/check-node"); // tslint:disable-next-line:variable-name exports.Rule = check_node_1.createCheckNodeRule(Ignore.checkNodeWithIgnore(checkNode), "Unexpected let, use const instead."); function checkNode(node, ctx) { var results = [ checkVariableStatement(node, ctx), checkForStatements(node, ctx) ]; return { invalidNodes: results.reduce(function (merged, result) { return merged.concat(result.invalidNodes); }, []), skipChildren: results.some(function (result) { return result.skipChildren === true; }) }; } function checkVariableStatement(node, ctx) { if (utils.isVariableStatement(node)) { return checkDeclarationList(node.declarationList, ctx); } return { invalidNodes: [] }; } function checkForStatements(node, ctx) { if ((utils.isForStatement(node) || utils.isForInStatement(node) || utils.isForOfStatement(node)) && node.initializer && utils.isVariableDeclarationList(node.initializer) && Lint.isNodeFlagSet(node.initializer, ts.NodeFlags.Let)) { return checkDeclarationList(node.initializer, ctx); } return { invalidNodes: [] }; } function checkDeclarationList(declarationList, ctx) { if (Lint.isNodeFlagSet(declarationList, ts.NodeFlags.Let)) { // It is a let declaration, now check each variable that is declared var invalidVariableDeclarationNodes = []; // If the declaration list contains multiple variables, eg. let x = 0, y = 1, mutableZ = 3; then // we should only provide one fix for the list even if two variables are invalid. // NOTE: When we have a mix of allowed and disallowed variables in the same DeclarationList // there is no sure way to know if we should do a fix or not, eg. if ignore-prefix=mutable // and the list is "let x, mutableZ", then "x" is invalid but "mutableZ" is valid, should we change // "let" to "const" or not? For now we change to const if at least one variable is invalid. var addFix = true; for (var _i = 0, _a = declarationList.declarations; _i < _a.length; _i++) { var variableDeclarationNode = _a[_i]; if (!Ignore.shouldIgnorePrefix(variableDeclarationNode, ctx.options, ctx.sourceFile)) { invalidVariableDeclarationNodes.push(check_node_1.createInvalidNode(variableDeclarationNode, addFix ? [ new Lint.Replacement(declarationList.getStart(ctx.sourceFile), "let".length, "const") ] : [])); addFix = false; } } return { invalidNodes: invalidVariableDeclarationNodes }; } return { invalidNodes: [] }; } //# sourceMappingURL=noLetRule.js.map