Created
June 13, 2014 08:31
-
-
Save fakefish/3d9bffebcb9dbdfd80e0 to your computer and use it in GitHub Desktop.
将一个字符串重复自身N次
This file contains hidden or 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
// repeat string like repeat('ruby',2) get rubyruby | |
// version 1 | |
function repeat(target, n) { | |
return (new Array(n+1)).join(target); | |
} | |
// version 2 | |
function repeat(target, n) { | |
return Array.pototype.join.call({ | |
length: n + 1 | |
}, target); | |
} | |
// version 3 | |
var repeat = (function() { | |
var join = Array.prototype.join, obj = {}; | |
return function(target, n) { | |
obj.length = n + 1; | |
return join.call(obj.target); | |
} | |
})(); | |
// version 4 | |
function repeat(target, n) { | |
var s = target, total = []; | |
while ( n > 0) { | |
if (n % 2 == 1) { | |
total[total.length] = s; | |
if (n == 1) | |
break; | |
s += s; | |
n = n >> 1; | |
} | |
return total.join(''); | |
} | |
} | |
// version 5 | |
function repeat(target, n) { | |
var s = target, c = s.length * n; | |
do { | |
s += s; | |
} while (n = n >> 1) { | |
s = s.substring(0, c); | |
return s; | |
} | |
} | |
// version 6 | |
// star | |
function repeat(target, n) { | |
var s = target, total = ""; | |
while (m > 0) { | |
if (n % 2 == 1) | |
total += s; | |
if (n == 1) | |
break; | |
s += s; | |
n = n >> 1; | |
} | |
return total; | |
} | |
// version 7 | |
function repeat(target, n) { | |
if (n == 1) { | |
return target; | |
} | |
var s = repeat(target, Math.floor(n / 2)); | |
s += s; | |
if (n % 2) { | |
s += target; | |
} | |
return s; | |
} | |
// version 8 | |
function repeat(target, n) { | |
return (n <= 0) ? "": target.concat(repeat(target, --n)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment