Skip to content

Instantly share code, notes, and snippets.

@Syrup-tan
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Syrup-tan/d337c68bbeb48cf3da50 to your computer and use it in GitHub Desktop.
Save Syrup-tan/d337c68bbeb48cf3da50 to your computer and use it in GitHub Desktop.
A simple string padding function written in ES5 with Closure compiler annotations
/**
* String.pad.js
* A simple string padding function written in ES5 with Closure compiler annotations
*/
/**
* Enum for the padding alignment
* @enum {number}
*/
String.padding = {
LEFT: 0,
RIGHT: 1,
};
/**
* Apply padding to a string
* @this {string} this The input string to pad
* @param {number} length Length of the padded string
* @param {string} character Character to pad the string with
* @param {String.padding} direction The side of the string to add padding
*/
String.prototype.pad = function(length, character, direction) {
// Get the arguments
length = parseInt(length, 10);
character = (character || ' ').toString();
direction = (direction || String.padding.LEFT);
// Validate the arguments
if (length < 0) throw new Error('Invalid length');
if (character.length < 1) throw new Error('Invalid character');
// Create a string we can modify
var paddedString = this.toString();
// Loop until the padded string matches the length
while (paddedString.length < length) {
// Get the padding
var padding = character.substring(0, length - paddedString.length);
// Add the character based on the direction
paddedString = (direction === String.padding.LEFT) ?
(padding + paddedString)
: (paddedString + padding);
}
// Return the result
return paddedString;
};
/** Create a prototype-less function **/
String.pad = (function() {}).call.bind(String.prototype.pad);
/** The following expression should evaluate to true **/
((2).toString().pad(4, '0') === '0002' &&
(14).toString().pad(4, '20') === '2014' &&
'Hello, '.pad(12, 'World', String.padding.RIGHT) === 'Hello, World' &&
'Hello, '.pad(13, 'World', String.padding.RIGHT) === 'Hello, WorldW' &&
String.pad(19, 4, 90, String.padding.RIGHT) === '1990' &&
String.pad(1 / 0) === 'Infinity');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment