source: trip-planner-front/node_modules/text-table/index.js@ ceaed42

Last change on this file since ceaed42 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.4 KB
Line 
1module.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
9 var dotsizes = reduce(rows_, function (acc, row) {
10 forEach(row, function (c, ix) {
11 var n = dotindex(c);
12 if (!acc[ix] || n > acc[ix]) acc[ix] = n;
13 });
14 return acc;
15 }, []);
16
17 var rows = map(rows_, function (row) {
18 return map(row, function (c_, ix) {
19 var c = String(c_);
20 if (align[ix] === '.') {
21 var index = dotindex(c);
22 var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2)
23 - (stringLength(c) - index)
24 ;
25 return c + Array(size).join(' ');
26 }
27 else return c;
28 });
29 });
30
31 var sizes = reduce(rows, function (acc, row) {
32 forEach(row, function (c, ix) {
33 var n = stringLength(c);
34 if (!acc[ix] || n > acc[ix]) acc[ix] = n;
35 });
36 return acc;
37 }, []);
38
39 return map(rows, function (row) {
40 return map(row, function (c, ix) {
41 var n = (sizes[ix] - stringLength(c)) || 0;
42 var s = Array(Math.max(n + 1, 1)).join(' ');
43 if (align[ix] === 'r' || align[ix] === '.') {
44 return s + c;
45 }
46 if (align[ix] === 'c') {
47 return Array(Math.ceil(n / 2 + 1)).join(' ')
48 + c + Array(Math.floor(n / 2 + 1)).join(' ')
49 ;
50 }
51
52 return c + s;
53 }).join(hsep).replace(/\s+$/, '');
54 }).join('\n');
55};
56
57function dotindex (c) {
58 var m = /\.[^.]*$/.exec(c);
59 return m ? m.index + 1 : c.length;
60}
61
62function reduce (xs, f, init) {
63 if (xs.reduce) return xs.reduce(f, init);
64 var i = 0;
65 var acc = arguments.length >= 3 ? init : xs[i++];
66 for (; i < xs.length; i++) {
67 f(acc, xs[i], i);
68 }
69 return acc;
70}
71
72function forEach (xs, f) {
73 if (xs.forEach) return xs.forEach(f);
74 for (var i = 0; i < xs.length; i++) {
75 f.call(xs, xs[i], i);
76 }
77}
78
79function map (xs, f) {
80 if (xs.map) return xs.map(f);
81 var res = [];
82 for (var i = 0; i < xs.length; i++) {
83 res.push(f.call(xs, xs[i], i));
84 }
85 return res;
86}
Note: See TracBrowser for help on using the repository browser.