_createPadding.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. var baseRepeat = require('./_baseRepeat'),
  2. baseToString = require('./_baseToString'),
  3. castSlice = require('./_castSlice'),
  4. hasUnicode = require('./_hasUnicode'),
  5. stringSize = require('./_stringSize'),
  6. stringToArray = require('./_stringToArray');
  7. /* Built-in method references for those with the same name as other `lodash` methods. */
  8. var nativeCeil = Math.ceil;
  9. /**
  10. * Creates the padding for `string` based on `length`. The `chars` string
  11. * is truncated if the number of characters exceeds `length`.
  12. *
  13. * @private
  14. * @param {number} length The padding length.
  15. * @param {string} [chars=' '] The string used as padding.
  16. * @returns {string} Returns the padding for `string`.
  17. */
  18. function createPadding(length, chars) {
  19. chars = chars === undefined ? ' ' : baseToString(chars);
  20. var charsLength = chars.length;
  21. if (charsLength < 2) {
  22. return charsLength ? baseRepeat(chars, length) : chars;
  23. }
  24. var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
  25. return hasUnicode(chars)
  26. ? castSlice(stringToArray(result), 0, length).join('')
  27. : result.slice(0, length);
  28. }
  29. module.exports = createPadding;