index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*!
  2. * repeat-string <https://github.com/jonschlinkert/repeat-string>
  3. *
  4. * Copyright (c) 2014-2015, Jon Schlinkert.
  5. * Licensed under the MIT License.
  6. */
  7. 'use strict';
  8. /**
  9. * Results cache
  10. */
  11. var res = '';
  12. var cache;
  13. /**
  14. * Expose `repeat`
  15. */
  16. module.exports = repeat;
  17. /**
  18. * Repeat the given `string` the specified `number`
  19. * of times.
  20. *
  21. * **Example:**
  22. *
  23. * ```js
  24. * var repeat = require('repeat-string');
  25. * repeat('A', 5);
  26. * //=> AAAAA
  27. * ```
  28. *
  29. * @param {String} `string` The string to repeat
  30. * @param {Number} `number` The number of times to repeat the string
  31. * @return {String} Repeated string
  32. * @api public
  33. */
  34. function repeat(str, num) {
  35. if (typeof str !== 'string') {
  36. throw new TypeError('expected a string');
  37. }
  38. // cover common, quick use cases
  39. if (num === 1) return str;
  40. if (num === 2) return str + str;
  41. var max = str.length * num;
  42. if (cache !== str || typeof cache === 'undefined') {
  43. cache = str;
  44. res = '';
  45. } else if (res.length >= max) {
  46. return res.substr(0, max);
  47. }
  48. while (max > res.length && num > 1) {
  49. if (num & 1) {
  50. res += str;
  51. }
  52. num >>= 1;
  53. str += str;
  54. }
  55. res += str;
  56. res = res.substr(0, max);
  57. return res;
  58. }