UNPKG

lumenize

Version:

Illuminating the forest AND the trees in your data.

112 lines (100 loc) 3.27 kB
// Generated by CoffeeScript 1.7.1 (function() { var table, utils; utils = require('tztime').utils; table = {}; /* @class table */ table.padToWidth = function(s, width, padCharacter, rightPad) { var padding; if (padCharacter == null) { padCharacter = ' '; } if (rightPad == null) { rightPad = false; } if (s.length > width) { return s.substr(0, width); } padding = new Array(width - s.length + 1).join(padCharacter); if (rightPad) { return s + padding; } else { return padding + s; } }; table.toString = function(rows, fields, sortBy, descending) { var field, index, key, maxWidths, row, s, sortedRows, value, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref; if (descending == null) { descending = false; } /* @method toString @param {Object[]} rows @param {Object} [fields] If not provided, it will use the fields found in the first row @param {String} [sortBy] If provided, it will sort the table by this field before returning @param {Boolean} [descending = false] By default, the sort will be ascending, setting this to true will sort descending @return {String} Returns a string for the table in Markdown format t = [ {col1: 'hello', col2: 12, col3: true}, {col1: 'goodbye', col2: 120, col3: false}, {col1: 'yep', col2: -23, col3: true}, ] console.log(require('../').table.toString(t, null, 'col2', true)) * | col1 | col2 | col3 | * | ------- | ---- | ----- | * | goodbye | 120 | false | * | hello | 12 | true | * | yep | -23 | true | */ if (fields == null) { fields = []; _ref = rows[0]; for (key in _ref) { value = _ref[key]; fields.push(key); } } maxWidths = []; for (index = _i = 0, _len = fields.length; _i < _len; index = ++_i) { field = fields[index]; maxWidths.push(field.length); for (_j = 0, _len1 = rows.length; _j < _len1; _j++) { row = rows[_j]; maxWidths[index] = Math.max(maxWidths[index], row[field].toString().length); } } if (sortBy != null) { sortedRows = utils._.sortBy(rows, sortBy); if (descending) { sortedRows = sortedRows.reverse(); } } else { sortedRows = rows; } s = '|'; for (index = _k = 0, _len2 = fields.length; _k < _len2; index = ++_k) { field = fields[index]; s += ' '; s += table.padToWidth(field, maxWidths[index], void 0, true) + ' |'; } s += '\n|'; for (index = _l = 0, _len3 = fields.length; _l < _len3; index = ++_l) { field = fields[index]; s += ' '; s += table.padToWidth('', maxWidths[index], '-', true) + ' |'; } for (_m = 0, _len4 = sortedRows.length; _m < _len4; _m++) { row = sortedRows[_m]; s += '\n|'; for (index = _n = 0, _len5 = fields.length; _n < _len5; index = ++_n) { field = fields[index]; s += ' '; s += table.padToWidth(row[field].toString(), maxWidths[index], void 0, true) + ' |'; } } return s; }; exports.table = table; }).call(this);