chg: refactored String.pad() method with builtin methods
This commit is contained in:
parent
708c02f670
commit
a0f5729e58
1 changed files with 14 additions and 21 deletions
|
@ -410,28 +410,21 @@ String.prototype.md5 = function() {
|
||||||
* String.BALANCE and String.RIGHT here as well.)
|
* String.BALANCE and String.RIGHT here as well.)
|
||||||
* @return String the resulting string
|
* @return String the resulting string
|
||||||
*/
|
*/
|
||||||
String.prototype.pad = function(str, len, mode) {
|
String.prototype.pad = function(str, length, mode) {
|
||||||
if (str == null || len == null)
|
if (mode === null || mode === String.RIGHT) return this.padEnd(length, str);
|
||||||
return this;
|
if (mode === String.LEFT) return this.padStart(length, str);
|
||||||
var diff = len - this.length;
|
|
||||||
if (diff == 0)
|
if (mode === String.BALANCE && str && length) {
|
||||||
return this;
|
const pos = Math.ceil(this.length / 2);
|
||||||
var left, right = 0;
|
const head = this.substr(0, pos);
|
||||||
if (mode == null || mode == String.RIGHT)
|
const tail = this.substr(pos);
|
||||||
right = diff;
|
const additionalLength = (length - this.length) / 2;
|
||||||
else if (mode == String.LEFT)
|
const startLength = head.length + Math.floor(additionalLength);
|
||||||
left = diff;
|
const endLength = tail.length + Math.ceil(additionalLength);
|
||||||
else if (mode == String.BALANCE) {
|
return head.padStart(startLength, str) + tail.padEnd(endLength, str);
|
||||||
right = Math.round(diff / 2);
|
|
||||||
left = diff - right;
|
|
||||||
}
|
}
|
||||||
res.push();
|
|
||||||
for (var i=0; i<left; i++)
|
return this;
|
||||||
res.write(str);
|
|
||||||
res.write(this);
|
|
||||||
for (var i=0; i<right; i++)
|
|
||||||
res.write(str);
|
|
||||||
return res.pop();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue