Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/fc8f1c3b6811d91e1902 to your computer and use it in GitHub Desktop.
Save JosePedroDias/fc8f1c3b6811d91e1902 to your computer and use it in GitHub Desktop.
tabular data to the console (js)

this

var cfg = [
    {title:'TS',   attr:'ts',   length: 5, isRight:true},
    {title:'NAME', attr:'name', length:15, isRight:false},
    {title:'DATA', attr:'data', length:35, isRight:false, transform:JSON.stringify}
];

var arr = [
    {ts:  35, name:'metadata_changed', data:{pageURI:'http://videos.sapo.pt/asd'}},
    {ts: 551, name:'state_changed',    data:'play'},
    {ts: 555, name:'play'},
    {ts:1037, name:'time_updated',     data:0.279541}
];
console.log( tabular(, this._events) );

should output this:

    TS | NAME            | DATA                                
-------+-----------------+-------------------------------------
    35 | metadata_chang… | {"pageURI":"http://videos.sapo.pt/… 
   551 | state_changed   | "play"                              
   555 | play            | null                                
  1037 | time_updated    | 0.279541                            
function pad(n, chr) {
if (n < 0) { return ''; }
debugFunctionCall('pad', arguments);
return new Array(n + 1).join(chr || ' ');
}
function justify(s, len, chr, isRight) {
debugFunctionCall('justify', arguments);
if (typeof s !== 'string') { s = '' + s; }
if (chr === undefined) { chr = ' '; }
var sLen = s.length;
if (len < sLen) { // truncate
s = s.substring(0, len-1) + '…';
sLen = len;
}
var p = pad(len - sLen, chr);
return ( isRight ? p + s : s + p );
}
function tabular(cfg, arr) {
var o = [];
// header
o.push(' ');
cfg.forEach(function(c) {
o.push( justify(c.title, c.length, ' ', c.isRight), ' | ');
});
o.pop(); o.push(' ');
// breaking line
o.push('\n-');
cfg.forEach(function(c) {
o.push( justify('', c.length, '-', c.isRight), '-+-');
});
o.pop(); o.push('-');
// each line
arr.forEach(function(a) {
o.push('\n ');
cfg.forEach(function(c) {
var v = a[c.attr];
if (c.transform) { v = c.transform(v); }
o.push( justify(v, c.length, ' ', c.isRight), ' | ');
});
o.pop(); o.push(' ');
});
return o.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment