-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathstringbuilder.js
More file actions
138 lines (110 loc) · 3.21 KB
/
Copy pathstringbuilder.js
File metadata and controls
138 lines (110 loc) · 3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
"use strict";
const { Stream } = require('stream');
function _applySpec(val, spec) {
const str = String(val);
switch (spec) {
case 'U': return str.toUpperCase();
case 'L': return str.toLowerCase();
case 'n': {
const num = parseFloat(val);
return isNaN(num) ? str : num.toLocaleString();
}
default: return str;
}
}
class StringBuilder extends Stream {
constructor(v) {
super();
this.s = [];
this.newline = process.platform === 'win32' ? '\r\n' : '\n';
this.append(v);
}
append(v) {
if (v != null) {
this.s.push(v);
}
return this;
}
appendLine(v) {
this.s.push(this.newline);
if (v != null) {
this.s.push(v);
}
return this;
}
appendFormat() {
const p = /({?){([^}]+)}(}?)/g;
let a = arguments, v = a[0], o = false;
if (a.length === 2) {
if (typeof a[1] == 'object' && a[1].constructor !== String) {
a = a[1];
o = true;
}
}
const s = v.split(p);
const r = [];
for (let i = 0; i < s.length; i += 4) {
r.push(s[i]);
if (s.length > i + 3) {
if (s[i + 1] === '{' && s[i + 3] === '}') {
r.push(s[i + 1], s[i + 2], s[i + 3]);
} else {
const token = s[i + 2];
const colon = token.indexOf(':');
const key = colon === -1 ? token : token.slice(0, colon);
const spec = colon === -1 ? null : token.slice(colon + 1);
let val = a[o ? key : parseInt(key, 10) + 1];
if (spec !== null && val != null) val = _applySpec(val, spec);
r.push(s[i + 1], val, s[i + 3]);
}
}
}
this.s.push(r.join(''));
return this;
}
prepend(v) {
if (v != null) {
this.s.unshift(v);
}
return this;
}
replace(search, replacement) {
if (this.s.length > 0) {
this.s = [this.s.join('').replace(search, String(replacement))];
}
return this;
}
replaceAll(search, replacement) {
if (this.s.length > 0) {
const str = this.s.join('');
if (typeof search === 'string') {
this.s = [str.split(search).join(String(replacement))];
} else {
const re = search.flags.includes('g')
? search
: new RegExp(search.source, search.flags + 'g');
this.s = [str.replace(re, String(replacement))];
}
}
return this;
}
appendJoin(arr, sep = '') {
if (arr != null) {
this.s.push(arr.join(sep));
}
return this;
}
get length() {
return this.s.reduce((sum, part) => sum + String(part).length, 0);
}
get isEmpty() {
return this.s.length === 0;
}
clear() {
this.s.length = 0;
}
toString() {
return this.s.length === 0 ? '' : this.s.join('');
}
}
module.exports = StringBuilder;