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