UNPKG

929 BJavaScriptView Raw
1'use strict';
2/**
3 * repeat-string module
4 * @module repeat-string
5 * @see module:index
6 */
7
8let res = '';
9let cache;
10
11/**
12 * Repeat the given `string` the specified `number`
13 * of times.
14 *
15 * **Example:**
16 *
17 * ```js
18 * var repeat = require('repeat-string');
19 * repeat('A', 5);
20 * //=> AAAAA
21 * ```
22 *
23 * @param {String} `string` The string to repeat
24 * @param {Number} `number` The number of times to repeat the string
25 * @return {String} Repeated string
26 * @api public
27 */
28
29module.exports = (str, num) => {
30 str = String(str);
31
32 // cover common, quick use cases
33 if (num === 1) return str;
34 if (num === 2) return str + str;
35
36 const max = str.length * num;
37 if (cache !== str || typeof cache === 'undefined') {
38 cache = str;
39 res = '';
40 }
41
42 while (max > res.length && num > 0) {
43 if (num & 1) {
44 res += str;
45 }
46
47 num >>= 1;
48 if (!num) break;
49 str += str;
50 }
51
52 return res.substr(0, max);
53};