pad.js 687 B

1234567891011121314151617181920212223242526
  1. var makeString = require('./helper/makeString');
  2. var strRepeat = require('./helper/strRepeat');
  3. module.exports = function pad(str, length, padStr, type) {
  4. str = makeString(str);
  5. length = ~~length;
  6. var padlen = 0;
  7. if (!padStr)
  8. padStr = ' ';
  9. else if (padStr.length > 1)
  10. padStr = padStr.charAt(0);
  11. switch (type) {
  12. case 'right':
  13. padlen = length - str.length;
  14. return str + strRepeat(padStr, padlen);
  15. case 'both':
  16. padlen = length - str.length;
  17. return strRepeat(padStr, Math.ceil(padlen / 2)) + str + strRepeat(padStr, Math.floor(padlen / 2));
  18. default: // 'left'
  19. padlen = length - str.length;
  20. return strRepeat(padStr, padlen) + str;
  21. }
  22. };