squarier
Version:
This package can help you format text in a square like manner.
84 lines • 3.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenMatrix = void 0;
var TokenMatrix = /** @class */ (function () {
function TokenMatrix(lines) {
this._matrix = lines;
this._lineStartPadding = 0;
}
Object.defineProperty(TokenMatrix.prototype, "matrix", {
get: function () {
return this._matrix;
},
enumerable: false,
configurable: true
});
TokenMatrix.prototype.setLineStartPadding = function (length) {
if (length < 0) {
throw new Error('length must be a greater than 0');
}
this._lineStartPadding = length;
};
TokenMatrix.prototype.getRow = function (idx) {
this.isValidRowIdx(idx);
return this._matrix[idx];
};
TokenMatrix.prototype.getColumn = function (idx) {
return this._matrix.map(function (row) { return row === null || row === void 0 ? void 0 : row[idx]; });
};
/**
* return the sum of all the tokens' length of a row
*
* return value -1 mean that this is weightless
*
* @param rowIdx the row number, should be in the matrix range
*/
TokenMatrix.prototype.getRowWeight = function (rowIdx) {
this.isValidRowIdx(rowIdx);
var row = this.getRow(rowIdx);
if (row.length === 1 && row[0].value === '') {
return -1;
}
return row.reduce(function (acc, t) { return acc + t.weight; }, 0);
};
TokenMatrix.prototype.getShortestRow = function () {
var smallestRowWeight = Infinity;
var smallestRowIndex = 0;
for (var i = 0; i < this._matrix.length; i++) {
var currRowWeight = this.getRowWeight(i);
if (currRowWeight < 0) {
continue;
}
if (currRowWeight < smallestRowWeight) {
smallestRowIndex = i;
smallestRowWeight = currRowWeight;
}
}
return smallestRowIndex;
};
TokenMatrix.prototype.transformRow = function (rowIdx, fn) {
this.isValidRowIdx(rowIdx);
this.getRow(rowIdx).forEach(function (t, i, arr) { return t.transform(function (v) { return fn(v, i, arr); }); });
};
TokenMatrix.prototype.transformColumn = function (colIdx, fn) {
this.getColumn(colIdx).forEach(function (t, i, arr) { return t === null || t === void 0 ? void 0 : t.transform(function (v) { return fn(v, i, arr); }); });
};
TokenMatrix.prototype.getLongestTokenOfColumn = function (colIdx) {
return this.getColumn(colIdx).sort(function (t1, t2) { return t2.weight - t1.weight; })[0];
};
TokenMatrix.prototype.isValidRowIdx = function (idx) {
if (idx >= this._matrix.length || idx < 0) {
throw new Error('Row Index must be in range of matrix');
}
};
TokenMatrix.prototype.toString = function () {
var _this = this;
return this._matrix
.map(function (row) { return row.map(function (token) { return token.value; }).join(' '); })
.map(function (line) { return ' '.repeat(_this._lineStartPadding) + line; })
.join('\n');
};
return TokenMatrix;
}());
exports.TokenMatrix = TokenMatrix;
//# sourceMappingURL=TokenMatrix.js.map