UNPKG

1.09 kBJavaScriptView Raw
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
8'use strict';
9
10/**
11 * Expose `repeat`
12 */
13
14module.exports = repeat;
15
16/**
17 * Repeat the given `string` the specified `number`
18 * of times.
19 *
20 * **Example:**
21 *
22 * ```js
23 * var repeat = require('repeat-string');
24 * repeat('A', 5);
25 * //=> AAAAA
26 * ```
27 *
28 * @param {String} `string` The string to repeat
29 * @param {Number} `number` The number of times to repeat the string
30 * @return {String} Repeated string
31 * @api public
32 */
33
34function repeat(str, num) {
35 if (typeof str !== 'string') {
36 throw new TypeError('repeat-string expects a string.');
37 }
38
39 var max = str.length * num;
40 cache = cache || str;
41 if (cache !== str) {
42 res = '';
43 cache = str;
44 }
45
46 while (num > 0 && max > res.length) {
47 if (num & 1) {
48 res += str;
49 }
50
51 if (max <= res.length) {
52 return res.substr(0, max);
53 }
54
55 num >>= 1;
56 str += str;
57 }
58
59 return res.substr(0, max);
60}
61
62/**
63 * Results cache
64 */
65
66var res = '';
67var cache;