Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80687 views
1
2
/**
3
* Repeats a string.
4
*
5
* @param {String} char(s)
6
* @param {Number} number of times
7
* @return {String} repeated string
8
*/
9
10
exports.repeat = function (str, times){
11
return Array(times + 1).join(str);
12
};
13
14
/**
15
* Pads a string
16
*
17
* @api public
18
*/
19
20
exports.pad = function (str, len, pad, dir) {
21
if (len + 1 >= str.length)
22
switch (dir){
23
case 'left':
24
str = Array(len + 1 - str.length).join(pad) + str;
25
break;
26
27
case 'both':
28
var right = Math.ceil((padlen = len - str.length) / 2);
29
var left = padlen - right;
30
str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
31
break;
32
33
default:
34
str = str + Array(len + 1 - str.length).join(pad);
35
};
36
37
return str;
38
};
39
40
/**
41
* Truncates a string
42
*
43
* @api public
44
*/
45
46
exports.truncate = function (str, length, chr){
47
chr = chr || '…';
48
return str.length >= length ? str.substr(0, length - chr.length) + chr : str;
49
};
50
51
/**
52
* Copies and merges options with defaults.
53
*
54
* @param {Object} defaults
55
* @param {Object} supplied options
56
* @return {Object} new (merged) object
57
*/
58
59
function clone(a){
60
var b;
61
if (Array.isArray(a)){
62
b = [];
63
for (var i = 0, l = a.length; i < l; i++)
64
b.push(typeof a[i] == 'object' ? clone(a[i]) : a[i]);
65
return b;
66
} else if (typeof a == 'object'){
67
b = {};
68
for (var i in a)
69
b[i] = typeof a[i] == 'object' ? clone(a[i]) : a[i];
70
return b;
71
}
72
return a;
73
};
74
75
exports.options = function (defaults, opts){
76
var c = clone(opts);
77
for (var i in defaults)
78
if (!(i in opts))
79
c[i] = defaults[i];
80
return c;
81
};
82
83
84
//
85
// For consideration of terminal "color" programs like colors.js,
86
// which can add ANSI escape color codes to strings,
87
// we destyle the ANSI color escape codes for padding calculations.
88
//
89
// see: http://en.wikipedia.org/wiki/ANSI_escape_code
90
//
91
exports.strlen = function(str){
92
var code = /\u001b\[\d+m/g;
93
var stripped = ("" + str).replace(code,'');
94
return stripped.length;
95
}
96
97