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