@sap/cds-dk
Version:
Command line client and development toolkit for the SAP Cloud Application Programming Model
59 lines (50 loc) • 1.64 kB
JavaScript
const os = require('os');
function intWidth(number) {
return Math.floor(Math.log10(number)) + 1;
}
function formatObjectsFixedWidth(objects, columns, distance, options = {}) {
const { numbering = false } = options;
const maxWidths = columns.reduce((result, column) => Object.assign(result, {
[column]: Math.max(...objects.map((object) => ('' + object[column]).length))
}), {});
const numberingWidth = intWidth(objects.length);
const separator = ' '.repeat(distance);
let result = '';
for (let o = 0; o < objects.length; o++) {
const object = objects[o];
if (numbering) {
result += ' '.repeat(numberingWidth - intWidth(o + 1));
result += o + 1;
result += '.';
result += separator;
}
for (let c = 0; c < columns.length; c++) {
const column = columns[c];
const value = '' + object[column];
result += value;
result += ' '.repeat(maxWidths[column] - value.length);
if (c < columns.length - 1) {
result += separator;
} else {
result += o < objects.length - 1
? os.EOL
: '';
}
}
}
return result;
}
/**
* from https://developer.mozilla.org/de/docs/Web/JavaScript/Guide/Regular_Expressions
*/
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
module.exports = {
formatObjectsFixedWidth,
escapeRegex,
capitalize
};