squarier
Version:
This package can help you format text in a square like manner.
81 lines • 3.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatSelection = void 0;
var Token_1 = require("./Token");
var TokenLine_1 = require("./TokenLine");
function formatSelection(text) {
if (!text) {
return "";
}
var lines = text.split("\n");
var leftSpacesCount = countSpacesBeforeFirstWord(lines[0]);
var tokensLines = lines.map(function (line) { return parseTokens(line); });
var shortestLine = tokensLines.map(function (line) { return line.length; }).sort()[0];
var maxWordLength = Array(shortestLine)
.fill(null)
.map(function (_, i) { return getLongestTokenOfColumn(tokensLines, i); });
var paddedTokens = tokensLines.map(function (line) {
return line.tokens.map(function (el, i, arr) {
return i < maxWordLength.length && i !== arr.length - 1
? pad(el.value, maxWordLength[i])
: el.value;
});
});
return paddedTokens
.map(function (wordLine) { return pad("", leftSpacesCount) + wordLine.join(" "); })
.join("\n");
}
exports.formatSelection = formatSelection;
/**
* Return a array of token,
* takes into account string and string escape characters
*/
function parseTokens(line) {
var tokens = [];
var tmp = "";
var isInString = false;
for (var i = 0; i < line.length; i++) {
var ch = line[i];
var prevCh = line[i - 1];
var nextCh = line[i + 1];
if (!isInString && ch === "/" && nextCh === "/") {
// This mean we are a comment, and we all the comment should be one token
// till the end of the line
if (tmp) {
tokens.push(new Token_1.Token(tmp));
}
var comment = line.slice(i);
tokens.push(new Token_1.Token(comment, 0));
return new TokenLine_1.TokenLine(tokens);
}
// If we not in a double quote string, we should treat white space as separators
if (ch === " " && !isInString) {
if (tmp) {
tokens.push(new Token_1.Token(tmp));
}
tmp = "";
}
else {
if (ch === '"' && prevCh !== "\\") {
isInString = !isInString;
}
tmp += ch;
}
}
tokens.push(new Token_1.Token(tmp));
return new TokenLine_1.TokenLine(tokens);
}
function countSpacesBeforeFirstWord(line) {
return line.split("").findIndex(function (el) { return el !== " "; });
}
function getLongestTokenOfColumn(grid, column) {
var lengths = grid.map(function (line) { var _a; return ((_a = line.tokens[column]) === null || _a === void 0 ? void 0 : _a.length) || 0; });
var sorted = lengths.sort(function (a, b) { return b - a; });
return sorted[0] || 0;
}
function pad(str, n, symbol) {
if (symbol === void 0) { symbol = " "; }
var paddingLength = Math.max(n - str.length, 0);
return str + symbol.repeat(paddingLength);
}
//# sourceMappingURL=index.js.map