11import { Column , ColumnPositioning , ColumnFactory } from "./column" ;
22
3- export class Table {
4- private _columns : Column [ ] = [ ] ;
5-
6- public static create ( text : string ) : Table {
7- const lines = text . split ( / \r \n | \r | \n / ) ;
8- const columns = 0 ;
9-
10- // split by separators to get a 2d array remove any empty lines
11- const rows = lines
12- . map ( l => l . split ( "|" ) )
13- . filter ( arr => ! ( arr . length == 1 && arr [ 0 ] == "" ) ) ;
14-
15- // remove the separator line from second line
16- const rowsWithoutSeparator = TableValidator . containsHeaderSeparator ( rows )
17- ? rows . filter ( ( v , i ) => i != 1 ) // remove the separator line from second line
18- : null ;
3+ export interface ITable {
4+ prettyPrint ( ) : string ;
5+ }
196
20- if ( ! TableValidator . areValidRows ( rowsWithoutSeparator ) )
21- return null ;
7+ export class Table implements ITable {
8+ private _columns : Column [ ] = [ ] ;
229
23- var result = new Table ( ) ;
24- result . _generateColumns ( rowsWithoutSeparator ) ;
25- return result ;
10+ constructor ( rowsWithoutSeparator : string [ ] [ ] ) {
11+ this . _generateColumns ( rowsWithoutSeparator ) ;
2612 }
2713
28- private constructor ( ) { }
29-
3014 private _generateColumns ( rawRows : string [ ] [ ] ) : void {
3115 for ( let column of ColumnFactory . generateColumns ( rawRows ) ) {
3216 this . _columns . push ( column ) ;
@@ -51,30 +35,4 @@ export class Table {
5135
5236 return buffer ;
5337 }
54- }
55-
56- class TableValidator {
57- public static containsHeaderSeparator ( rawRows : string [ ] [ ] ) : boolean {
58- if ( ! rawRows || rawRows . length < 1 || ! rawRows [ 1 ] )
59- return false ;
60- const secondRow = rawRows [ 1 ] ;
61- return secondRow . every ( ( v , i ) => this . isSeparator ( v , i == 0 || i == secondRow . length - 1 ) ) ;
62- }
63-
64- private static isSeparator ( cellValue : string , isFirstOrLast : boolean ) : boolean {
65- if ( cellValue . trim ( ) == "-" )
66- return true ;
67- // If the first or last column is empty then it still can be a header containing separator,
68- // for example table starting or ending with borders ("|") would produce this.
69- if ( cellValue . trim ( ) == "" && isFirstOrLast )
70- return true ;
71- return false ;
72- }
73-
74- public static areValidRows ( rawRows : string [ ] [ ] ) : boolean {
75- return ! ! rawRows &&
76- rawRows . length > 1 && // at least two rows are required
77- rawRows [ 0 ] . length > 1 && // at least two columns are required
78- rawRows . every ( r => r . length == rawRows [ 0 ] . length ) ; // all rows of a column must match the length of the first row of that column
79- }
80- }
38+ }
0 commit comments