From 61a148bb022a757aa0efc73330ba898904acd10b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=BF=B7=E6=B8=A1?= Date: Wed, 4 Sep 2019 15:36:27 +0800 Subject: [PATCH] Refactoring using padEnd and padStart --- fmt/sprintf.ts | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/fmt/sprintf.ts b/fmt/sprintf.ts index 596f90c858e3..e1edb13479ff 100644 --- a/fmt/sprintf.ts +++ b/fmt/sprintf.ts @@ -365,14 +365,12 @@ class Printf { pad(s: string): string { const padding = this.flags.zero ? "0" : " "; - while (s.length < this.flags.width) { - if (this.flags.dash) { - s += padding; - } else { - s = padding + s; - } + + if (this.flags.dash) { + return s.padEnd(this.flags.width, padding); } - return s; + + return s.padStart(this.flags.width, padding); } padNum(nStr: string, neg: boolean): string { let sign: string; @@ -393,13 +391,12 @@ class Printf { const pad = zero ? "0" : " "; const len = zero ? this.flags.width - sign.length : this.flags.width; - while (nStr.length < len) { - if (this.flags.dash) { - nStr += pad; // left justify - right pad - } else { - nStr = pad + nStr; // right just - left pad - } + if (this.flags.dash) { + nStr = nStr.padEnd(len, pad); + } else { + nStr = nStr.padStart(len, pad); } + if (zero) { // see above nStr = sign + nStr;