Skip to content

Commit

Permalink
feat(table): add .fromJson() method
Browse files Browse the repository at this point in the history
  • Loading branch information
c4spar committed Jul 26, 2020
1 parent 699c0d1 commit 4be3edd
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/table/lib/row.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Cell, ICell } from './cell.ts';

export type IRow<T extends ICell = ICell> = T[] | Row<T>;
export type IDataRow = Record<string, string | number>;

export interface IRowOptions {
indent?: number;
Expand Down
12 changes: 11 additions & 1 deletion packages/table/lib/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { encode } from 'https://deno.land/std@v0.61.0/encoding/utf8.ts';
import { border, IBorder } from './border.ts';
import { Cell } from './cell.ts';
import { TableLayout } from './layout.ts';
import { IRow, Row } from './row.ts';
import { IDataRow, IRow, Row } from './row.ts';

export interface IBorderOptions extends Partial<IBorder> {}

Expand Down Expand Up @@ -42,10 +42,20 @@ export class Table<T extends IRow = IRow> extends Array<T> {
return table;
}

public static fromJson( rows: IDataRow[] ): Table {
return new this().fromJson( rows );
}

public static render<T extends IRow>( rows: ITable<T> ): void {
Table.from( rows ).render();
}

public fromJson( rows: IDataRow[] ): this {
this.header( Object.keys( rows[ 0 ] ) );
this.body( rows.map( row => Object.values( row ) as T ) );
return this;
}

public header( header: IRow ): this {
this.headerRow = header instanceof Row ? header : Row.from( header );
return this;
Expand Down

0 comments on commit 4be3edd

Please sign in to comment.