Skip to content

Commit

Permalink
Declare internal classes to represent a table elements
Browse files Browse the repository at this point in the history
Following classes are added to make the easy to enhance in future.

* DataCell - table data
* Column - manage column attributes
* Row - manage cells

These are not exported.
So, the public interfaces and its results are not changed at all.
  • Loading branch information
takamin committed Apr 24, 2016
1 parent e6dbed3 commit 7f920f9
Showing 1 changed file with 63 additions and 12 deletions.
75 changes: 63 additions & 12 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,24 @@
this.colmaxlen = [];
};
privates.ListItBuffer.prototype.nl = function() {
this.lines.push([]);
this.lines.push(new Row());
return this;
};
privates.ListItBuffer.prototype.d = function(s) {
if(this.lines.length <= 0) {
this.nl();
}
var row = this.lines.length - 1;
var col = this.lines[row].length;
var col = this.lines[row].getCellLength();
if(col >= this.colmaxlen.length) {
this.colmaxlen.push(s.length);
} else if(this.colmaxlen[col] < s.length) {
this.colmaxlen[col] = s.length;
var column = new Column();
this.colmaxlen.push(column);
col = this.colmaxlen.length - 1;
}
this.lines[row].push(s);
this.colmaxlen[col].expandWidth(s.length);
var cell = new DataCell();
cell.setData(s);
this.lines[row].pushCell(cell);
return this;
};
privates.ListItBuffer.prototype.toString = function() {
Expand All @@ -36,17 +39,65 @@
var rows = [];
this.lines.forEach(function(line) {
var cols = [];
for(var col = 0; col < line.length; col++) {
var m = this.colmaxlen[col];
var s = line[col];
while(s.length < m) {
s += ' ';
}
for(var col = 0; col < line.getCellLength(); col++) {
var s = this.colmaxlen[col].formatCell(line.getCell(col));
cols.push(s);
}
rows.push(cols.join(' '));
}, this);
return rows.join("\n");;
};
module.exports = exports;

//
// DataCell class
//
var DataCell = function() {
this.data = "";
};
DataCell.prototype.getData = function() {
return this.data;
};
DataCell.prototype.setData = function(data) {
this.data = data;
};

//
// Column class
//
var Column = function() {
this.width = 0;
};
Column.prototype.getWidth = function() {
return this.width;
};
Column.prototype.expandWidth = function(width) {
if(width > this.width) {
this.width = width;
}
};
Column.prototype.formatCell = function(cell) {
var m = this.getWidth();
var s = cell.getData();
while(s.length < m) {
s += ' ';
}
return s;
};

//
// Row class
//
var Row = function() {
this.cells = [];
};
Row.prototype.getCellLength = function() {
return this.cells.length;
};
Row.prototype.getCell= function(idx) {
return this.cells[idx];
};
Row.prototype.pushCell = function(cell) {
return this.cells.push(cell);
};
}());

0 comments on commit 7f920f9

Please sign in to comment.