index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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('repeat-string expects 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. }
  46. while (max > res.length && num > 0) {
  47. if (num & 1) {
  48. res += str;
  49. }
  50. num >>= 1;
  51. if (!num) break;
  52. str += str;
  53. }
  54. return res.substr(0, max);
  55. }