UNPKG

1.47 kBJavaScriptView Raw
1'use strict';
2// https://github.com/tc39/proposal-string-pad-start-end
3var uncurryThis = require('../internals/function-uncurry-this');
4var toLength = require('../internals/to-length');
5var toString = require('../internals/to-string');
6var $repeat = require('../internals/string-repeat');
7var requireObjectCoercible = require('../internals/require-object-coercible');
8
9var repeat = uncurryThis($repeat);
10var stringSlice = uncurryThis(''.slice);
11var ceil = Math.ceil;
12
13// `String.prototype.{ padStart, padEnd }` methods implementation
14var createMethod = function (IS_END) {
15 return function ($this, maxLength, fillString) {
16 var S = toString(requireObjectCoercible($this));
17 var intMaxLength = toLength(maxLength);
18 var stringLength = S.length;
19 var fillStr = fillString === undefined ? ' ' : toString(fillString);
20 var fillLen, stringFiller;
21 if (intMaxLength <= stringLength || fillStr === '') return S;
22 fillLen = intMaxLength - stringLength;
23 stringFiller = repeat(fillStr, ceil(fillLen / fillStr.length));
24 if (stringFiller.length > fillLen) stringFiller = stringSlice(stringFiller, 0, fillLen);
25 return IS_END ? S + stringFiller : stringFiller + S;
26 };
27};
28
29module.exports = {
30 // `String.prototype.padStart` method
31 // https://tc39.es/ecma262/#sec-string.prototype.padstart
32 start: createMethod(false),
33 // `String.prototype.padEnd` method
34 // https://tc39.es/ecma262/#sec-string.prototype.padend
35 end: createMethod(true)
36};