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