Created
November 29, 2012 08:45
-
-
Save jeffreyiacono/4167637 to your computer and use it in GitHub Desktop.
add #times to String prototype
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
| 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