Skip to content

Commit 07c92e8

Browse files
committed
Modified existing padLeft() and padRight() functions to support strings other than a single space as padding.
Used this new functionality to zero-pad the timestamp created by nowString().
1 parent 8aad412 commit 07c92e8

File tree

2 files changed

+32
-10
lines changed

2 files changed

+32
-10
lines changed

src/compiler/core.ts

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2250,18 +2250,40 @@ namespace ts {
22502250
}
22512251
}
22522252

2253-
export function padLeft(s: string, length: number) {
2254-
while (s.length < length) {
2255-
s = " " + s;
2253+
2254+
/**
2255+
* Returns 's' left-padded with copies of 'padString' until it reaches the given 'length'.
2256+
* If omitted, 'padString' defaults to a single space.
2257+
* If 'length' is less than or equal to 's.length' or 'padString' is empty, returns 's' unchanged.
2258+
*/
2259+
export function padLeft(s: string, length: number, padString = " ") {
2260+
if (length <= s.length || padString.length === 0) {
2261+
return s;
2262+
}
2263+
else {
2264+
length -= s.length; // how much padding we need
2265+
if (length > padString.length) { // need more than one copy of padString
2266+
padString += padString.repeat(length / padString.length);
2267+
}
2268+
return padString.slice(0, length) + s;
22562269
}
2257-
return s;
22582270
}
22592271

2260-
export function padRight(s: string, length: number) {
2261-
while (s.length < length) {
2262-
s = s + " ";
2272+
/**
2273+
* Returns 's' right-padded with copies of 'padString' until it reaches the given 'length'.
2274+
* If omitted, 'padString' defaults to a single space.
2275+
* If 'length' is less than or equal to 's.length' or 'padString' is empty, returns 's' unchanged.
2276+
*/
2277+
export function padRight(s: string, length: number, padString = " ") {
2278+
if (length <= s.length || padString.length === 0) {
2279+
return s;
2280+
}
2281+
else {
2282+
length -= s.length;
2283+
if (length > padString.length) { // need more than one copy of padString
2284+
padString += padString.repeat(length / padString.length);
2285+
}
2286+
return s + padString.slice(0, length);
22632287
}
2264-
2265-
return s;
22662288
}
22672289
}

src/jsTyping/shared.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,6 @@ namespace ts.server {
5757
export function nowString() {
5858
// E.g. "12:34:56.789"
5959
const d = new Date();
60-
return `${("00" + d.getHours()).slice(-2)}:${("00" + d.getMinutes()).slice(-2)}:${("00" + d.getSeconds()).slice(-2)}.${("000" + d.getMilliseconds()).slice(-3)}`;
60+
return `${padLeft(d.getHours().toString(), 2, "0")}:${padLeft(d.getMinutes().toString(), 2, "0")}:${padLeft(d.getSeconds().toString(), 2, "0")}.${padLeft(d.getMilliseconds().toString(), 3, "0")}`;
6161
}
6262
}

0 commit comments

Comments
 (0)