Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jozsefsallai committed May 30, 2020
0 parents commit 67ffb08
Show file tree
Hide file tree
Showing 12 changed files with 450 additions and 0 deletions.
Binary file added .github/assets/01.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added .github/assets/02.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added .github/assets/03.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added .github/assets/04.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
.vscode
.DS_Store
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 József Sallai <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
89 changes: 89 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# tbl

Tiny and versatile command-line table generator.

This module is very early in development, so bugs may appear here and there.

## Usage

**Simple table:**

```ts
import { Table } from 'https://deno.land/x/tbl/mod.ts';

const table = new Table(); // this is an array!

table.push([ 'hello', 'world' ]);
table.push([ 'testing', 123 ]);

console.log(table.toString());
```

![Example 1](.github/assets/01.png)

**Table with header:**

```ts
const table = new Table({
header: [ 'name', 'age', 'occupation' ]
});

table.push([ 'Joe', 19, 'Software Engineer' ]);
table.push([ 'Niko', '?', 'Not a cat' ]);
table.push([ 'Ryan Dahl', 39, 'Software Engineer' ]);

console.log(table.toString());
```

![Example 2](.github/assets/02.png)

**Table with custom characters:**

```ts
const table = new Table({
header: [ 'name', 'age', 'occupation' ],
chars: {
middleMiddle: '', topMiddle: '' , topLeft: '' , topRight: ''
, bottomMiddle: '' , bottomLeft: '' , bottomRight: ''
, left: '' , leftMiddle: '' , rowMiddle: ''
, right: '' , rightMiddle: '' , middle: ''
}
});
```

![Example 3](.github/assets/03.png)

**Table with custom cell widths:**

```ts
const languages = new Table({
header: [ 'name', 'extension', 'description' ],
widths: [ 20, 0, 60 ] // 0 = width is not fixed
});
```

![Example 4](.github/assets/04.png)

**Table from array of objects:**

```ts
const users = [
{ name: 'Joe', age: 19, occupation: 'Software Engineer' },
{ name: 'Niko', age: '?', occupation: 'Not a cat' }
{ name: 'Ryan Dahl', age: 39, occupation: 'Software Engineer' }
];

const table = new Table({
header: [ 'name', 'age', 'occupation' ]
// specifying the header is necessary
});

table.fromObjects(users);
console.log(table.toString());
```

![Example 5](.github/assets/02.png)

## License

MIT.
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './src/table.ts';
26 changes: 26 additions & 0 deletions src/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { TableCharacters } from './table.ts';

function initCharacters(chars: TableCharacters = {}): TableCharacters {
const characters: TableCharacters = {};

characters.middleMiddle = chars.middleMiddle || '─';
characters.rowMiddle = chars.rowMiddle || '┼';
characters.topRight = chars.topRight || '┐';
characters.topLeft = chars.topLeft || '┌';
characters.leftMiddle = chars.leftMiddle || '├';
characters.topMiddle = chars.topMiddle || '┬';
characters.bottomRight = chars.bottomRight || '┘';
characters.bottomLeft = chars.bottomLeft || '└';
characters.bottomMiddle = chars.bottomMiddle || '┴';
characters.rightMiddle = chars.rightMiddle || '┤';
characters.left = chars.left || '│';
characters.right = chars.right || '│';
characters.middle = chars.middle || '│';

return characters;
}

export {
initCharacters,
TableCharacters
};
120 changes: 120 additions & 0 deletions src/render.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { TableCharacters } from './init.ts';
import iro, { bold } from 'https://deno.land/x/[email protected]/src/iro.ts';
import { truncateTable } from '../utils/truncate.ts';

interface RendererOpts {
items: any[][];
header?: any[];
widths?: number[];
characters?: TableCharacters;
}

class Renderer {
private header: any[];
private items: any[][];
private characters: TableCharacters;

private count: number;
private widths: number[];

constructor(opts: RendererOpts) {
this.items = opts.items;
this.header = opts.header || [];
this.characters = opts.characters || {};
this.count = this.header.length || opts.items[0].length;
this.widths = this.calculateMaxWidths();

if (opts.widths?.length) {
for (let i = 0; i < opts.widths.length; i++) {
if (opts.widths[i] !== 0) {
this.widths[i] = opts.widths[i];
}
}
}
}

private calculateMaxWidths(): number[] {
const widths: number[] = new Array(this.count).fill(0);
const items = this.header.length
? [this.header, ...this.items]
: this.items;

items.forEach((item, idx) => {
if (item.length > this.count) {
console.warn(`Row no. ${idx + 1} contains more cells than the first row. The additional cells will be truncated.`);
}

if (item.length < this.count) {
throw new Error(`Row no. ${idx + 1} has fewer cells than the first row.`);
}

item
.slice(0, this.count)
.forEach((v, i) => {
const width = String(v).length;

if (width > widths[i]) {
widths[i] = width;
}
});
});

return widths;
}

public renderTop(): string {
let str: string = '' + this.characters.topLeft;

str += this.widths.map(w => {
return ''.padEnd(w + 2, this.characters.middleMiddle);
}).join(this.characters.topMiddle);

str += this.characters.topRight;

return str;
}

public renderRow(row: any[], isHeader: boolean = false, renderVerticalSeparator: boolean = true): string {
let str = '' + this.characters.left;

str += row
.slice(0, this.count)
.map((cell, idx) => {
cell = String(cell);
cell = ` ${cell} `.padEnd(this.widths[idx] + 2, ' ');

return isHeader
? iro(cell, bold)
: cell;
})
.join(this.characters.middle);

str += this.characters.right;

if (renderVerticalSeparator) {
str += `\n${this.characters.leftMiddle}`;

str += this.widths.map(w => {
return ''.padEnd(w + 2, this.characters.middleMiddle);
}).join(this.characters.rowMiddle);

str += this.characters.rightMiddle;
}

return str;
}

public renderBottom(): string {
let str: string = '' + this.characters.bottomLeft;

str += this.widths.map(w => {
return ''.padStart(w + 2, this.characters.middleMiddle);
}).join(this.characters.bottomMiddle);

str += this.characters.bottomRight;

return str;
}
}

export default Renderer;
120 changes: 120 additions & 0 deletions src/table.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { initCharacters } from './init.ts';
import Renderer from './render.ts';
import { truncateTable, TruncatedTable } from '../utils/truncate.ts';

export interface TableCharacters {
middleMiddle?: string;
rowMiddle?: string;
topRight?: string;
topLeft?: string;
leftMiddle?: string;
topMiddle?: string;
bottomRight?: string;
bottomLeft?: string;
bottomMiddle?: string;
rightMiddle?: string;
left?: string;
right?: string;
middle?: string;
}

export interface TableOptions {
header?: any[];
widths?: number[];
chars?: TableCharacters;
}

export class Table extends Array {
private options: TableOptions;

constructor(opts?: TableOptions) {
super();

this.options = {};

this.options.header = opts?.header || [];
this.options.widths = opts?.widths;
this.options.chars = opts?.chars
? initCharacters(opts.chars)
: initCharacters();

if (opts?.widths?.length) {

}
}

fromObjects(arr: any[]): Table {
if (!this.options.header?.length) {
throw new Error(`Table.fromObjects requires that you have the "headers" option set up.`);
}

const rows: any[][] = [];

arr.forEach(row => {
if (Object.keys(row).length < 1) {
return;
}

const current: any[] = [];

this.options.header?.forEach(cell => {
current.push(row[cell] || '');
});

rows.push(current);
});

this.push(...rows);

return this;
}

toString(): string {
if (!this.length) {
return '';
}

let items = this as any[][];
let truncatedTable: TruncatedTable | undefined;
let truncatedHeader: TruncatedTable | undefined;

const renderer = new Renderer({
header: this.options.header,
widths: this.options.widths,
items,
characters: this.options.chars
});

const stringComponents = [];
stringComponents.push(renderer.renderTop());

if (this.options?.header?.length) {
let headers = [this.options.header];

if (this.options.widths?.length) {
truncatedHeader = truncateTable(headers, this.options.widths);
headers = truncatedHeader.table;
}

stringComponents.push(
headers
.map((item, idx) => renderer.renderRow(item, true, idx === headers.length - 1))
.join('\n')
);
}

if (this.options.widths?.length) {
truncatedTable = truncateTable(items, this.options.widths);
items = truncatedTable.table;
}

stringComponents.push(
items
.map((item, idx) => renderer.renderRow(item, false, idx !== items.length - 1 && (truncatedTable?.renderBorders[idx])))
.join('\n')
);

stringComponents.push(renderer.renderBottom());
return stringComponents.join('\n');
}
}
Loading

0 comments on commit 67ffb08

Please sign in to comment.