Created
September 6, 2012 12:06
-
-
Save redraiment/3655538 to your computer and use it in GitHub Desktop.
JavaScript: Multiplication for String
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
/* a clever way to implement string multiplication in JavaScript */ | |
String.prototype.times = function(n) { | |
return Array.prototype.join.call({length:n+1}, this); | |
}; | |
"js".times(5) // => "jsjsjsjsjs" |
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
/* a simpler version that might be just as efficient */ | |
String.prototype.times = function(n) { | |
return (new Array(n+1)).join(this); | |
}; |
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
/* based on string doubling by recursion */ | |
String.prototype.times = function(n) { | |
if ( n == 1 ) { | |
return this; | |
} | |
var midRes = this.times(Math.floor(n/2)); | |
midRes += midRes; | |
if ( n % 2 ) { | |
midRes += this; | |
} | |
return midRes; | |
} |
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
/* based on string doubling by loop */ | |
String.prototype.times = function(n) { | |
var s = this, total = ""; | |
while(n > 0) { | |
if (n % 2 == 1) total += s; | |
if (n == 1) break; | |
s += s; | |
n = n>>1; | |
} | |
return total; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment