From eea856e341a5381c6a5744db1ee6fe590cf8ffd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=BF=B7=E6=B8=A1?= Date: Wed, 4 Sep 2019 22:32:28 +0800 Subject: [PATCH] Refactoring using padEnd and padStart (denoland/deno_std#583) Original: https://github.com/denoland/deno_std/commit/4e21ace634b635ef540adc7727cd3d8eb9df99bd --- fmt/sprintf.ts | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/fmt/sprintf.ts b/fmt/sprintf.ts index 596f90c858..e1edb13479 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;