UNPKG

ts-simple-ast

Version:

TypeScript compiler wrapper for AST navigation and code generation.

53 lines (51 loc) 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const textSeek_1 = require("./../textSeek"); const tree_1 = require("./../tree"); function removeChildren(opts) { const { children, removePrecedingSpaces = false, removeFollowingSpaces = false, removePrecedingNewLines = false, removeFollowingNewLines = false } = opts; if (children.length === 0) return; const sourceFile = children[0].getSourceFile(); const fullText = sourceFile.getFullText(); const newText = getPrefix() + getSuffix(); const tempSourceFile = sourceFile.global.compilerFactory.createTempSourceFileFromText(newText, 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() { const pos = children[0].getNonWhitespaceStart(); if (removePrecedingSpaces || removePrecedingNewLines) return textSeek_1.getPreviousMatchingPos(fullText, pos, getCharRemovalFunction(removePrecedingSpaces, removePrecedingNewLines)); return pos; } function getRemovalEnd() { const 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 (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; //# sourceMappingURL=removeChildren.js.map