Skip to content

Instantly share code, notes, and snippets.

@redraiment
Created September 6, 2012 12:06
Show Gist options
  • Save redraiment/3655538 to your computer and use it in GitHub Desktop.
Save redraiment/3655538 to your computer and use it in GitHub Desktop.
JavaScript: Multiplication for String
/* 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"
/* a simpler version that might be just as efficient */
String.prototype.times = function(n) {
return (new Array(n+1)).join(this);
};
/* 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;
}
/* 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