StringPad.js 1.2 KB

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