Pad A String In JavaScript Using Augmentation

Ever needed to pad a string in JavaScript with a certain character? This article will describe a simple extension to the String prototype that will do just that! -Perhaps with a bit more flexibility.

To get right to the point, here is the implementation:

if ( "undefined" === typeof String.prototype.pad ) {
    String.prototype.pad = function _String__pad ( obj ) {
        var result = this,
            width = 2,
            padChar = "0",
            prefix = false;

        if ( obj ) {
            if ( "object" === typeof obj ) {
                if ( obj.prefix ) { prefix = obj.prefix };
                if ( obj.width ) { width = obj.width };
                if ( obj.char ) { padChar = obj.char };
            } else if ( "string" === typeof obj ) {
                padChar = obj;
            } else if ( "number" === typeof obj ) {
                width = obj;
            }
        }

        while ( this && width > result.length ) {
            if ( prefix ) {
                result = padChar + result;
            } else {
                result += padChar;
            }
        }

        return result;
    };
}

Before I get to the guts of the above code snippet, I wish to examine a few reasons it is possible:

  • Instance methods can be created on-the-fly. This means a String object such as “Hello World” would immediately contain the above method named “pad”. The method could be called like “Hello World”.pad().
  • JavaScript is a dynamic language. In this case, it means any variable can be of any type at any point during runtime.
  • A method exists as a “function”. This can be explicitly tested.
  • Instance methods exist in an Object’s prototype.

Now for the details.

First, it is always wise to make sure your code is not performing unnecessary work. To this end a check is made to make sure the function does not already exist on String’s prototype. If it does not already exist, it is created.

Four variables are then declare presenting the features of this method:

  • Returns a new string
  • Supports a custom string width
  • Supports a custom padding character
  • Supports either prefix padding or suffix padding

These variables are optionally overridden by the object, String, or Number argument given. This is one of many times when the beauty of JavaScript’s weakly-typed nature really shines. Any of the features can be overridden given the appropriate argument type and value. If the argument is an object, the method expects the object to contain the three properties: prefix, width, and char. If the argument is a String the method assumes the client is attempting to override the padding character. If the argument is a number, the method assumes the client is attempting to override the padded string width.

Lets talk more about the padded string width. This is important for the next bit of code.

Assume there is a string indicating an order number of “99D”. The requirements say order numbers less than 5 characters must be padded on the left with zeros. The implementation supports this:

"99D".pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var orderNumber = "99D";
orderNumber.pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var padOptions = { char: "0", width: 5, prefix: true };
"99D".pad(padOptions); //result: "0099D"

To get this set width, a while loop is used. While the string is less than the given width, the method adds the specified pad character to either the beginning or the end of the string based on whether it should be a prefix or not. Once the string is at least the length of the specified padded string width, the method breaks out of the while loop and returns the resultant string.

There are other ways to use this implementation of the pad method as well:

Specify the padding character –

"E".pad("T"); //result: "ET"

Specify the padded string width –

"1".pad(2); //result: "10"

There are a few improvements or additional features that could be implemented for this method but, this is a flexible start.

Advertisements

Safe & DRY JavaScript Augmentation

Augmentation is one of my favorite features of JavaScript. Being able to, at any point, add static and instance methods to new and existing types is a wonderful feature of this dynamic language. In this post I’ll describe two common ways of augmenting JavaScript types and how those ways can be made safer while adhering to the DRY principle.

Instance Methods

One of the most common uses of augmentation is adding instance methods to types. Using a type’s prototype chain, methods can be added to all new and existing instances of the augmented type:

Array.prototype.indexOf = function (item) {
    /* Body Excluded for Brevity */
};

In this code snippet the “indexOf” function was added to the prototype of the Array object. Each Array instance will have this method (even if the instance was created before the method was defined). This method will also replace any previous implementations of the “indexOf” function. It is best to make sure the function doesn’t already exist:

if (typeof Array.prototype.indexOf === "undefined") {
    Array.prototype.indexOf = function (item) {
        /* Body Excluded for Brevity */
    };
}

Here the typeof operator is used to determine whether the method is undefined. If it is, the method implementation is added to the Array object.

Static Methods

Functions can also be added as static methods of a given type:

String.Format = function (format) {
    /* Body Excluded for Brevity */
};

In the code snippet above the “Format” method was added as a static method of the String object. Similar to adding instance methods, it is best to make sure this method does not already exist:

if (typeof String.Format === "undefined") {
    String.Format = function (format) {
        /* Body Excluded for Brevity */
    };
}

Don’t Repeat Yourself

If your augmentation code is augmenting multiple types or with multiple methods, the type check will be used over and over. Why not make that part of the code reusable? By using augmentation, a reusable method can be implemented to perform this type check and the augmentation:

if (typeof Function.safeAugment === "undefined") {
    Function.safeAugment = function (obj, func, impl) {
        var method = obj[func];
        if (typeof method === "undefined") {
            obj[func] = impl;
        }
    };
}

Here the augmentation code is wrapped inside the “safeAugment” function. This function is implemented as a static method of the “Function” object. The “safeAugment” function takes three parameters: the object to augment, the function name to add to the object, and the implementation of the function. Here is an example of its use:

Function.safeAugment(Array.prototype, "indexOf", function (item) {
    /* indexOf Body Excluded for Brevity*/
});

The safeAugment function is used to define our indexOf instance method for the Array object. The safeAugment function can be used to defined static methods as well:

Function.safeAugment(String, "Format", function (item) {
    /* String.Format Body Excluded for Brevity*/
});

Here the “Format” method is added to the String object as a static method.

Enhancing the Augmentation Code

As it stands now, the safeAugment function performs its duty: augment the given object with the given method with the given implementation. The first and most obvious improvement would be to validate its parameters. This means making sure that each parameter is of an expected type so the object to augment exists, the function name is a string (and not null), and the implementation is a function. Improvements beyond this is more dependent on your given circumstances. Perhaps you want to allow the implementation to be null, or add logging capabilities, or locate the point in which all the elements in the multiverse will collide, etc, etc. The point is to safely augment JavaScript types while adhering to the DRY principle.