ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
51 lines (50 loc) • 2.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var textSeek_1 = require("./../textSeek");
var tree_1 = require("./../tree");
function removeChildren(opts) {
var children = opts.children, _a = opts.removePrecedingSpaces, removePrecedingSpaces = _a === void 0 ? false : _a, _b = opts.removeFollowingSpaces, removeFollowingSpaces = _b === void 0 ? false : _b, _c = opts.removePrecedingNewLines, removePrecedingNewLines = _c === void 0 ? false : _c, _d = opts.removeFollowingNewLines, removeFollowingNewLines = _d === void 0 ? false : _d;
if (children.length === 0)
return;
var sourceFile = children[0].getSourceFile();
var fullText = sourceFile.getFullText();
var newText = getPrefix() + getSuffix();
var tempSourceFile = sourceFile.global.compilerFactory.createTempSourceFileFromText(newText, { filePath: sourceFile.getFilePath() });
tree_1.replaceTreeWithChildIndex({
replacementSourceFile: tempSourceFile,
parent: children[0].getParentSyntaxList() || children[0].getParentOrThrow(),
childIndex: children[0].getChildIndex(),
childCount: -1 * children.length
});
function getPrefix() {
return fullText.substring(0, getRemovalPos());
}
function getSuffix() {
return fullText.substring(getRemovalEnd());
}
function getRemovalPos() {
var pos = children[0].getNonWhitespaceStart();
if (removePrecedingSpaces || removePrecedingNewLines)
return textSeek_1.getPreviousMatchingPos(fullText, pos, getCharRemovalFunction(removePrecedingSpaces, removePrecedingNewLines));
return pos;
}
function getRemovalEnd() {
var end = children[children.length - 1].getEnd();
if (removeFollowingSpaces || removeFollowingNewLines)
return textSeek_1.getNextMatchingPos(fullText, end, getCharRemovalFunction(removeFollowingSpaces, removeFollowingNewLines));
return end;
}
function getCharRemovalFunction(removeSpaces, removeNewLines) {
return function (char) {
if (removeNewLines && (char === "\r" || char === "\n"))
return false;
if (removeSpaces && !charNotSpaceOrTab(char))
return false;
return true;
};
}
function charNotSpaceOrTab(char) {
return char !== " " && char !== "\t";
}
}
exports.removeChildren = removeChildren;