string-pad.js 1.4 KB

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