Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Created November 4, 2012 12:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abozhilov/4011690 to your computer and use it in GitHub Desktop.
Save abozhilov/4011690 to your computer and use it in GitHub Desktop.
repeat
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