StringPad.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var callBound = require('call-bind/callBound');
  5. var ToLength = require('./ToLength');
  6. var ToString = require('./ToString');
  7. var $strSlice = callBound('String.prototype.slice');
  8. // https://262.ecma-international.org/11.0/#sec-stringpad
  9. module.exports = function StringPad(O, maxLength, fillString, placement) {
  10. if (placement !== 'start' && placement !== 'end') {
  11. throw new $TypeError('Assertion failed: `placement` must be "start" or "end"');
  12. }
  13. var S = ToString(O);
  14. var intMaxLength = ToLength(maxLength);
  15. var stringLength = S.length;
  16. if (intMaxLength <= stringLength) {
  17. return S;
  18. }
  19. var filler = typeof fillString === 'undefined' ? ' ' : ToString(fillString);
  20. if (filler === '') {
  21. return S;
  22. }
  23. var fillLen = intMaxLength - stringLength;
  24. // the String value consisting of repeated concatenations of filler truncated to length fillLen.
  25. var truncatedStringFiller = '';
  26. while (truncatedStringFiller.length < fillLen) {
  27. truncatedStringFiller += filler;
  28. }
  29. truncatedStringFiller = $strSlice(truncatedStringFiller, 0, fillLen);
  30. if (placement === 'start') {
  31. return truncatedStringFiller + S;
  32. }
  33. return S + truncatedStringFiller;
  34. };