Skip to content

Instantly share code, notes, and snippets.

@sundarj
Last active August 29, 2015 14:27
Show Gist options
  • Save sundarj/76a382075f7e0962ee7a to your computer and use it in GitHub Desktop.
Save sundarj/76a382075f7e0962ee7a to your computer and use it in GitHub Desktop.
Terminal-style table generator
function Tabula(init) {
this.fields = init.fields;
this.values = init.values;
function maxFieldLength(values, fields) {
return values.map(function(value, index) {
return Math.max(value.length, fields[index % fields.length].length);
}).map(function(value, index, full) {
return Math.max(value, full[index + full.length/2]);
}).filter(function(v) { return !isNaN(v) });
}
function padFields(fields, values, padding) {
return fields.map(function(field, index) {
var maxlengths = maxFieldLength(values, fields);
while (field.length < maxlengths[index]) {
field = field + padding;
}
return field;
});
}
function padValues(values, fields, padding) {
return values.map(function(value, index) {
while (value.length < fields[index % fields.length].length) {
value = value + padding;
}
return value;
});
}
this.fields = padFields(this.fields, this.values, this.padding);
this.values = padValues(this.values, this.fields, this.padding);
this.representation = [];
}
Tabula.prototype.padding = " ";
Tabula.prototype.ends = {
start: '|' + Tabula.prototype.padding,
end: Tabula.prototype.padding + '|'
}
Tabula.prototype.sep = Tabula.prototype.padding + Tabula.prototype.ends.start;
Tabula.prototype.length = function() {
return this.fields.map(function(field) {
return field.length;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
Tabula.prototype.hr = function() {
return '+' + '-'.repeat(this.length() + this.sep.repeat(this.fields.length).length-1) + '+';
};
Tabula.prototype.header = function() {
this.representation.push(this.hr(), this.ends.start + this.fields.join(this.sep) + this.ends.end);
}
function arraySplit(array, delim) {
var ret = [];
array.forEach(function(value, index) {
if (index % delim === 0)
ret.push(array.slice(index, index+delim));
});
return ret;
}
Tabula.prototype.cells = function() {
var values = arraySplit(this.values, this.fields.length);
values.forEach(function(value) {
var row = this.ends.start + value.join(this.sep) + this.ends.end;
this.representation.push(this.hr(), row);
}, this);
}
Tabula.prototype.footer = function() {
this.representation.push(this.hr());
}
Tabula.prototype.render = function() {
this.header();
this.cells();
this.footer();
return this.representation.join("\n");
}
/* tests */
var table = new Tabula({
fields: ['name', 'age', 'color'],
values: ['samantha', '23', 'rouge', 'toby', '18', 'silver']
});
console.log(table.render());
var table2 = new Tabula({
fields: ['type', 'smell'],
values: ['red', 'apple', 'magenta', 'blackcurrant']
});
console.log(table2.render());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment