repeat.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. var baseToString = require('../internal/baseToString');
  2. /* Native method references for those with the same name as other `lodash` methods. */
  3. var nativeFloor = Math.floor,
  4. nativeIsFinite = global.isFinite;
  5. /**
  6. * Repeats the given string `n` times.
  7. *
  8. * @static
  9. * @memberOf _
  10. * @category String
  11. * @param {string} [string=''] The string to repeat.
  12. * @param {number} [n=0] The number of times to repeat the string.
  13. * @returns {string} Returns the repeated string.
  14. * @example
  15. *
  16. * _.repeat('*', 3);
  17. * // => '***'
  18. *
  19. * _.repeat('abc', 2);
  20. * // => 'abcabc'
  21. *
  22. * _.repeat('abc', 0);
  23. * // => ''
  24. */
  25. function repeat(string, n) {
  26. var result = '';
  27. string = baseToString(string);
  28. n = +n;
  29. if (n < 1 || !string || !nativeIsFinite(n)) {
  30. return result;
  31. }
  32. // Leverage the exponentiation by squaring algorithm for a faster repeat.
  33. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
  34. do {
  35. if (n % 2) {
  36. result += string;
  37. }
  38. n = nativeFloor(n / 2);
  39. string += string;
  40. } while (n);
  41. return result;
  42. }
  43. module.exports = repeat;