createPadding.js 973 B

1234567891011121314151617181920212223242526272829
  1. var repeat = require('../string/repeat');
  2. /* Native method references for those with the same name as other `lodash` methods. */
  3. var nativeCeil = Math.ceil,
  4. nativeIsFinite = global.isFinite;
  5. /**
  6. * Creates the padding required for `string` based on the given `length`.
  7. * The `chars` string is truncated if the number of characters exceeds `length`.
  8. *
  9. * @private
  10. * @param {string} string The string to create padding for.
  11. * @param {number} [length=0] The padding length.
  12. * @param {string} [chars=' '] The string used as padding.
  13. * @returns {string} Returns the pad for `string`.
  14. */
  15. function createPadding(string, length, chars) {
  16. var strLength = string.length;
  17. length = +length;
  18. if (strLength >= length || !nativeIsFinite(length)) {
  19. return '';
  20. }
  21. var padLength = length - strLength;
  22. chars = chars == null ? ' ' : (chars + '');
  23. return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
  24. }
  25. module.exports = createPadding;