Created
January 3, 2019 10:00
-
-
Save viniciusgati/d9c4b932378469aa7b26ed519317516a to your computer and use it in GitHub Desktop.
Adiciona funcionalidade a classe object fazendo com que qualquer objeto tenha a função pad, bem legal.
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
| /* | |
| * method prototype for any Object to pad it's toString() | |
| * representation with additional characters to the specified length | |
| * | |
| * @param padToLength required int | |
| * entire length of padded string (original + padding) | |
| * @param padChar optional char | |
| * character to use for padding, default is white space | |
| * @param padLeft optional boolean | |
| * if true padding added to left | |
| * if omitted or false, padding added to right | |
| * | |
| * @return padded string or | |
| * original string if length is >= padToLength | |
| */ | |
| Object.prototype.pad = function(padToLength, padChar, padLeft) { | |
| // get the string value | |
| s = this.toString() | |
| // default padToLength to 0 | |
| // if omitted, original string is returned | |
| padToLength = padToLength || 0; | |
| // default padChar to empty space | |
| padChar = padChar || ' '; | |
| // ignore padding if string too long | |
| if (s.length >= padToLength) { | |
| return s; | |
| } | |
| // create the pad of appropriate length | |
| var pad = Array(padToLength - s.length).join(padChar); | |
| // add pad to right or left side | |
| if (padLeft) { | |
| return pad + s; | |
| } else { | |
| return s + pad; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment