Created
November 4, 2012 12:27
-
-
Save abozhilov/4011690 to your computer and use it in GitHub Desktop.
repeat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function repeat(obj, times) { | |
var res = typeof obj == 'string' ? '' : []; | |
times = Math.max(1, times); | |
do { | |
if (times & 0x1) res = res.concat(obj); | |
obj = obj.concat(obj); | |
} while ((times >>= 1)); | |
return res; | |
} | |
//Example | |
console.log(repeat('a', 10)); //aaaaaaaaaa | |
console.log(repeat([1, 2, 3], 3)); //[1, 2, 3, 1, 2, 3, 1, 2, 3] | |
//Init array with 0 | |
console.log(repeat([0], 10)); //[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment