StringPad.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var callBound = require('call-bind/callBound');
  4. var isInteger = require('../helpers/isInteger');
  5. var $strSlice = callBound('String.prototype.slice');
  6. // https://262.ecma-international.org/15.0/#sec-stringpad
  7. module.exports = function StringPad(S, maxLength, fillString, placement) {
  8. if (typeof S !== 'string') {
  9. throw new $TypeError('Assertion failed: `S` must be a String');
  10. }
  11. if (!isInteger(maxLength) || maxLength < 0) {
  12. throw new $TypeError('Assertion failed: `maxLength` must be a non-negative integer');
  13. }
  14. if (typeof fillString !== 'string') {
  15. throw new $TypeError('Assertion failed: `fillString` must be a String');
  16. }
  17. if (placement !== 'start' && placement !== 'end' && placement !== 'START' && placement !== 'END') {
  18. throw new $TypeError('Assertion failed: `placement` must be ~START~ or ~END~');
  19. }
  20. var stringLength = S.length; // step 1
  21. if (maxLength <= stringLength) { return S; } // step 2
  22. if (fillString === '') { return S; } // step 3
  23. var fillLen = maxLength - stringLength; // step 4
  24. // 5. Let _truncatedStringFiller_ be the String value consisting of repeated concatenations of _fillString_ truncated to length _fillLen_.
  25. var truncatedStringFiller = '';
  26. while (truncatedStringFiller.length < fillLen) {
  27. truncatedStringFiller += fillString;
  28. }
  29. truncatedStringFiller = $strSlice(truncatedStringFiller, 0, fillLen);
  30. if (placement === 'start' || placement === 'START') { return truncatedStringFiller + S; } // step 6
  31. return S + truncatedStringFiller; // step 7
  32. };