Last active
March 31, 2016 17:20
-
-
Save Eccenux/52062de47b11cd79ffb0f2c7995dc0f3 to your computer and use it in GitHub Desktop.
Pad left class :-]
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
/** | |
* Pad class. | |
* | |
* @author Maciej "Nux" Jaros | |
* @license CC-BY | |
* | |
* Note! The class becomes faster with new itterations. | |
*/ | |
NuxPadder = function (character) | |
{ | |
if (typeof character !== 'string' || character.length < 1) { | |
character = ' '; | |
} | |
this.paddingString = character; | |
} | |
/** | |
* Prepare internals for given length | |
*/ | |
NuxPadder.prototype.prepare = function (neededCharacters) | |
{ | |
if (this.paddingString.length >= neededCharacters) { | |
return; | |
} | |
while (this.paddingString.length < neededCharacters) { | |
this.paddingString += this.paddingString; | |
} | |
} | |
/** | |
* Pad left `str` to have at least `length` characters. | |
*/ | |
NuxPadder.prototype.padLeft = function(str, length) { | |
var neededCharacters = length - str.length; | |
if (neededCharacters > 0) { | |
this.prepare(neededCharacters); | |
} | |
return this.paddingString.substr(0, neededCharacters) + str; | |
} |
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
var pad = new NuxPadder(' '); | |
pad.padLeft('123', 1) // -> '123' | |
pad.padLeft('123', 3) // -> '123' | |
pad.padLeft('123', 5) // -> ' 123' | |
// Note! If you know beforehand how much padding you will need use `prepare` function | |
var columns = ["abc", "def", "123456789"]; | |
var columnWidths = [5, 5, 15]; | |
var maxPad = 15; | |
var pad = new NuxPadder(' '); | |
pad.prepare(maxPad) | |
for (var i = 0; i < columns.length; i++) { | |
columns[i] = pad.padLeft(columns[i], columnWidths[i]); | |
} | |
// columns = [" abc", " def", " 123456789"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment