Vi Veri Veniversum Vivus Vici
  1. /**
  2.   * Returns ASCII-table in CLI-like style
  3.   * @param {Array} data array of rows like key=>value
  4.   * @param {Object} headers hash of table's headers like key=>title
  5.   * @return {String}
  6.   */
  7. cliTable = function (data, headers) {
  8. var cellLengths = {},
  9. result,
  10. cell,
  11. cellLength,
  12. bar = '+',
  13. header = '|',
  14. padRight = function (value, maxLen, character) {
  15. if (!Ext4.isString(value)) {
  16. value = value.toString();
  17. }
  18. while (value.length < maxLen) {
  19. value += character;
  20. }
  21. return value;
  22. };
  23. Ext4.each(data, function (row) {
  24. Ext4.Object.each(headers, function (key) {
  25. cellLength = row[key].toString().length;
  26. if (!cellLengths[key] || (cellLengths[key] < cellLength)) {
  27. cellLengths[key] = cellLength;
  28. }
  29. });
  30. });
  31. Ext4.Object.each(headers, function (key, value) {
  32. cellLength = cellLengths[key];
  33. bar += Ext4.String.repeat('-', cellLength + 2) + '+';
  34. if (value.length > cellLength) {
  35. value = value.substr(0, cellLength);
  36. }
  37. header += ' ' + padRight(value, cellLength, ' ') + ' |';
  38. });
  39. result = bar + 'n' + header + 'n' + bar + 'n';
  40. Ext4.each(data, function (row) {
  41. result += '|';
  42. Ext4.Object.each(row, function (key, value) {
  43. result += ' ' + padRight(value, cellLengths[key], ' ') + ' |';
  44. });
  45. result += 'n';
  46. });
  47. result += bar;
  48. return result;
  49. }


@темы: ExtJS 4, JavaScript