columns.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. var generate = require("es5-ext/array/generate")
  3. , from = require("es5-ext/array/from")
  4. , iterable = require("es5-ext/iterable/validate-object")
  5. , isValue = require("es5-ext/object/is-value")
  6. , stringifiable = require("es5-ext/object/validate-stringifiable")
  7. , repeat = require("es5-ext/string/#/repeat")
  8. , getStrippedLength = require("./get-stripped-length");
  9. var push = Array.prototype.push;
  10. module.exports = function (inputRows /*, options*/) {
  11. var options = Object(arguments[1])
  12. , colsMeta = []
  13. , colsOptions = options.columns || []
  14. , rows = [];
  15. from(iterable(inputRows), function (row) {
  16. var rowRows = [[]];
  17. from(iterable(row), function (cellStr, columnIndex) {
  18. var cellRows = stringifiable(cellStr).split("\n");
  19. while (cellRows.length > rowRows.length) rowRows.push(generate(columnIndex, ""));
  20. cellRows.forEach(function (cellRow, rowRowIndex) {
  21. rowRows[rowRowIndex][columnIndex] = cellRow;
  22. });
  23. });
  24. push.apply(rows, rowRows);
  25. });
  26. return (
  27. rows
  28. .map(function (row) {
  29. return from(iterable(row), function (str, index) {
  30. var col = colsMeta[index], strLength;
  31. if (!col) col = colsMeta[index] = { width: 0 };
  32. str = stringifiable(str);
  33. strLength = getStrippedLength(str);
  34. if (strLength > col.width) col.width = strLength;
  35. return { str: str, length: strLength };
  36. });
  37. })
  38. .map(function (row) {
  39. return row
  40. .map(function (item, index) {
  41. var pad, align = "left", colOptions = colsOptions && colsOptions[index];
  42. align = colOptions && colOptions.align === "right" ? "right" : "left";
  43. pad = repeat.call(" ", colsMeta[index].width - item.length);
  44. if (align === "left") return item.str + pad;
  45. return pad + item.str;
  46. })
  47. .join(isValue(options.sep) ? options.sep : " | ");
  48. })
  49. .join("\n") + "\n"
  50. );
  51. };