Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Created November 29, 2012 08:45
Show Gist options
  • Select an option

  • Save jeffreyiacono/4167637 to your computer and use it in GitHub Desktop.

Select an option

Save jeffreyiacono/4167637 to your computer and use it in GitHub Desktop.
add #times to String prototype
​String.prototype.times = function(n) {
// join checks its first argument for a length property, so we supply it with one.
// what normally happens is something like this:
//
// [1, 2, 3].length //=> 3
// [1, 2, 3].join(", ") //=> "1, 2, 3"
//
// so the following is equivalent ...
//
// Array.prototype.join.call([1, 2, 3], ", ") //=> "1, 2, 3"
//
// we can even do:
//
// Array.prototype.join.call({'0' : 1, '1' : 2, '2' : 3, length : 3}, ", ") //=> "1, 2, 3"
//
// so then just passing in an object with a length property of n + 1 will tell the Array
// to join all indexed elements in the object (of which there are none) with the second argument
// (the separator), which will result in the separator being concatenated n + 1 times, which
// is then returned. Pretty tricky!
return Array.prototype.join.call({length: n+1}, this);
}
console.log("join this ".times(10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment