From c6cbf1ed0ec66acfd4b830fc55678a8593a28782 Mon Sep 17 00:00:00 2001 From: Dave Pacheco Date: Tue, 17 Jul 2012 17:38:35 -0700 Subject: [PATCH] support for rows as objects --- examples/ex.objects.js | 30 ++++++++++++++++++++++++++++++ examples/ex.stream.js | 13 +++++++++++++ lib/tab.js | 19 +++++++++++++------ 3 files changed, 56 insertions(+), 6 deletions(-) create mode 100644 examples/ex.objects.js create mode 100644 examples/ex.stream.js diff --git a/examples/ex.objects.js b/examples/ex.objects.js new file mode 100644 index 0000000..74f885e --- /dev/null +++ b/examples/ex.objects.js @@ -0,0 +1,30 @@ +var mod_tab = require('../lib/tab'); + +mod_tab.emitTable({ + 'columns': [ { + 'label': 'PID', + 'align': 'right', + 'width': 6 + }, { + 'label': 'TTY', + 'width': 7 + }, { + 'label': 'TIME', + 'align': 'right', + 'width': 10 + }, { + 'label': 'CMD' + } ], + + 'rows': [ { + 'PID': '60881', + 'TTY': 'ttys000', + 'TIME': '0:00.19', + 'CMD': '-bash' + }, { + 'PID': '61674', + 'TTY': 'ttys000', + 'TIME': '0:00.17', + 'CMD': 'vim README.md' + } ] +}); diff --git a/examples/ex.stream.js b/examples/ex.stream.js new file mode 100644 index 0000000..ef5f648 --- /dev/null +++ b/examples/ex.stream.js @@ -0,0 +1,13 @@ +var mod_tab = require('../lib/tab'); + +var out = new mod_tab.TableOutputStream({ + 'columns': [ 'PID', 'TTY', 'TIME', 'CMD' ] +}); + +out.writeRow([ '60881', 'ttys000', '0:00.19', '-bash' ]); +out.writeRow({ + 'PID': '61674', + 'TTY': 'ttys000', + 'TIME': '0:00.17', + 'CMD': 'vim README.md' +}); diff --git a/lib/tab.js b/lib/tab.js index 56d3bcd..98ed7c1 100644 --- a/lib/tab.js +++ b/lib/tab.js @@ -93,12 +93,19 @@ TableOutputStream.prototype.writeRow = function (row) this.tos_header = false; } - n = Math.min(row.length, this.tos_cols.length); - for (i = 0; i < n; i++) - this.tos_cols[i].emit(row[i]); - - for (; i < this.tos_cols.length; i++) - this.tos_cols[i].emit(''); + if (Array.isArray(row)) { + n = Math.min(row.length, this.tos_cols.length); + for (i = 0; i < n; i++) + this.tos_cols[i].emit(row[i]); + + for (; i < this.tos_cols.length; i++) + this.tos_cols[i].emit(''); + } else { + for (i = 0; i < this.tos_cols.length; i++) { + this.tos_cols[i].emit( + row[this.tos_cols[i]['label']] || ''); + } + } this.tos_out.write(this.tos_endrecord); };