UNPKG

2.06 kBJavaScriptView Raw
1var stripAnsi = require('strip-ansi');
2
3/**
4 * Repeats a string.
5 *
6 * @param {String} char(s)
7 * @param {Number} number of times
8 * @return {String} repeated string
9 */
10
11exports.repeat = function (str, times){
12 return Array(times + 1).join(str);
13};
14
15/**
16 * Pads a string
17 *
18 * @api public
19 */
20
21exports.pad = function (str, len, pad, dir) {
22 if (len + 1 >= str.length)
23 switch (dir){
24 case 'left':
25 str = Array(len + 1 - str.length).join(pad) + str;
26 break;
27
28 case 'both':
29 var right = Math.ceil((padlen = len - str.length) / 2);
30 var left = padlen - right;
31 str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
32 break;
33
34 default:
35 str = str + Array(len + 1 - str.length).join(pad);
36 };
37
38 return str;
39};
40
41/**
42 * Truncates a string
43 *
44 * @api public
45 */
46
47exports.truncate = function (str, length, chr){
48 chr = chr || '…';
49 return str.length >= length ? str.substr(0, length - chr.length) + chr : str;
50};
51
52/**
53 * Copies and merges options with defaults.
54 *
55 * @param {Object} defaults
56 * @param {Object} supplied options
57 * @return {Object} new (merged) object
58 */
59
60function options(defaults, opts) {
61 for (var p in opts) {
62 if (p === '__proto__' || p === 'constructor' || p === 'prototype') {
63 continue;
64 }
65 if (opts[p] && opts[p].constructor && opts[p].constructor === Object) {
66 defaults[p] = defaults[p] || {};
67 options(defaults[p], opts[p]);
68 } else {
69 defaults[p] = opts[p];
70 }
71 }
72 return defaults;
73};
74exports.options = options;
75
76//
77// For consideration of terminal "color" programs like colors.js,
78// which can add ANSI escape color codes to strings,
79// we destyle the ANSI color escape codes for padding calculations.
80//
81// see: http://en.wikipedia.org/wiki/ANSI_escape_code
82//
83exports.strlen = function(str){
84 str = typeof str === 'string' ? str : String(str);
85 var stripped = stripAnsi(str);
86 var split = stripped.split("\n");
87 return split.reduce(function (memo, s) { return (s.length > memo) ? s.length : memo }, 0);
88}