You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.4 KiB

4 years ago
  1. module.exports = function (rows_, opts) {
  2. if (!opts) opts = {};
  3. var hsep = opts.hsep === undefined ? ' ' : opts.hsep;
  4. var align = opts.align || [];
  5. var stringLength = opts.stringLength
  6. || function (s) { return String(s).length; }
  7. ;
  8. var dotsizes = reduce(rows_, function (acc, row) {
  9. forEach(row, function (c, ix) {
  10. var n = dotindex(c);
  11. if (!acc[ix] || n > acc[ix]) acc[ix] = n;
  12. });
  13. return acc;
  14. }, []);
  15. var rows = map(rows_, function (row) {
  16. return map(row, function (c_, ix) {
  17. var c = String(c_);
  18. if (align[ix] === '.') {
  19. var index = dotindex(c);
  20. var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2)
  21. - (stringLength(c) - index)
  22. ;
  23. return c + Array(size).join(' ');
  24. }
  25. else return c;
  26. });
  27. });
  28. var sizes = reduce(rows, function (acc, row) {
  29. forEach(row, function (c, ix) {
  30. var n = stringLength(c);
  31. if (!acc[ix] || n > acc[ix]) acc[ix] = n;
  32. });
  33. return acc;
  34. }, []);
  35. return map(rows, function (row) {
  36. return map(row, function (c, ix) {
  37. var n = (sizes[ix] - stringLength(c)) || 0;
  38. var s = Array(Math.max(n + 1, 1)).join(' ');
  39. if (align[ix] === 'r' || align[ix] === '.') {
  40. return s + c;
  41. }
  42. if (align[ix] === 'c') {
  43. return Array(Math.ceil(n / 2 + 1)).join(' ')
  44. + c + Array(Math.floor(n / 2 + 1)).join(' ')
  45. ;
  46. }
  47. return c + s;
  48. }).join(hsep).replace(/\s+$/, '');
  49. }).join('\n');
  50. };
  51. function dotindex (c) {
  52. var m = /\.[^.]*$/.exec(c);
  53. return m ? m.index + 1 : c.length;
  54. }
  55. function reduce (xs, f, init) {
  56. if (xs.reduce) return xs.reduce(f, init);
  57. var i = 0;
  58. var acc = arguments.length >= 3 ? init : xs[i++];
  59. for (; i < xs.length; i++) {
  60. f(acc, xs[i], i);
  61. }
  62. return acc;
  63. }
  64. function forEach (xs, f) {
  65. if (xs.forEach) return xs.forEach(f);
  66. for (var i = 0; i < xs.length; i++) {
  67. f.call(xs, xs[i], i);
  68. }
  69. }
  70. function map (xs, f) {
  71. if (xs.map) return xs.map(f);
  72. var res = [];
  73. for (var i = 0; i < xs.length; i++) {
  74. res.push(f.call(xs, xs[i], i));
  75. }
  76. return res;
  77. }