Download code

As I mentioned in my previous post, I’m in the process of creating some JavaScript functions that extend the basic JavaScript data types. Well, I’ve create a few extensions for the String and Number data types. Also, since I’m building a JavaScript library, I went ahead and packaged the source code files into a library as well.

JavaScript Extensions

How do you extend the basic data types you ask? There are two ways. You can either create a static method, which is available from the from the data type itself, or a prototype method, which is available from all instances of that data type.

For example, the repeat function is a static method of the built-in JavaScript String class. It was created like this:

1
2
3
4
5
6
7
String.repeat = function(chr, count)
{
  var s = '';     
  for(var i = 0; i < count; i++) 
    s += chr;     
  return s;
}

You can then execute the repeat method like so:

1
2
var str = String.repeat('x', 5);
alert(str);  // Alerts: "xxxxx"

On the other hand, the rightPad function was created as a prototype method of the String class. If you recall from the Creating JavaScript Classes series, prototype methods are accessible from all object instances. This means any instance of a String will have this method.

1
2
3
4
5
6
7
8
9
10
String.prototype.rightPad = function(width, chr, trunc)
{
  var s = this.toString();
  var w = width - s.length;
  if (w > 0)
    s = s + String.repeat(chr, w);
  else if (trunc)
    s = s.substr(0, width);
  return s;
}

Now, there are two things to note in the above. First, the declaration uses String.prototype.rightPad to add the rightPad function to the prototype of the String class. Second, because the rightPad method is now available to a String object instance, the this variable is available in the function, and it will point to the current String instance.

Also of particular interest is line 3, which uses this.toString() to create a copy of the current string. It is this copy that is modified and returned by the function. This is common functionality in JavaScript, and I wanted to follow that same pattern here. For example, the replace method does not alter the string, but returns a new string with the replacements made.

The String extensions include basic string manipulation function like padding, trimming and formatting. I’ve also include a function to convert a string to a number, while considering how a user might enter a number. So these values could include thousands separators, currency symbols, or even fractions. I often find that users appreciate the ability to enter fractions rather than decimals. Its easier for a user to enter 1/8 rather than remembering or calculating the decimal value 0.125. And I’m a big believer that the user should not be calculating anything. That’s what the computer is for!

The Number extensions include a toFormat function that will take the number and convert it to a string. Again, this can take a number like 0.125 and convert it back to the fraction 1/8, if desired. I could have overridden the built-in toString function, but it has its own purpose that developers may still want to use, so I left it alone.

Here are some examples of using these extensions. To format a number, you can use:

1
2
3
var num = 1234.56;
var str = num.toFormat(3, true);
alert (str);  // Alerts: "1,234.560"

Or, if you want a fraction, set the first argument (the precision) to -1, like so:

1
2
3
var num = 1.333;
var str = num.toFormat(-1);
alert (str);  // Alerts: "1-1/3"

Using the string extensions, you can parse the fraction:

1
2
3
var str = '1-1/3';
var num = str.toNumber();
alert (num);  // Alerts: "1.3333"

To pad a string, use something like this:

1
2
3
var str = '123';
var pstr = str.leftPad('0', 5);
alert (pstr);  // Alerts: "00123"

Of course, you can chain all these functions, too:

1
2
3
var num = 123.4;
var str = num.toFormat(2).leftPad('*', 8);
alert (pstr);  // Alerts: "**123.40"

This is just a sample of the extensions that are included. All of them are pretty straight-forward, and the code is well-documented (in my opinion, let me know if you feel otherwise). And, of course, all of the unit tests are in there as well. Please keep in mind that these are first versions, so don’t expect perfection yet! I can already see where I’d like to make some additions and changes to these functions. I’m still in the early stages here, so I’ll try to keep things backward compatible. But that may not be possible. You’ve been warned!

JavaScript Library Framework

The other thing I did in this version is to package these extensions along with the Class function from the Creating JavaScript Classes series, into a actual library. I also added a namespace, and, come to think of it, I should probably also add a namespace function. Will add that to my list of things to do. Anyway, to use the Class function, you will now access it using LivingMachines.Class(). Otherwise, it’s usage is the same as previously described in the Creating JavaScript Classes series. Going forward, all additional code will be added to this new library package.

Well, I hope you find these useful and educational. This is only the start of the library, so make sure to subscribe to the RSS feed so that you can keep up to date on new developments. Next up, I’m going to work on some date formatting functions. This means I’ll be adding some functions to the Data data type, and to the String data type as well.

Included JavaScript Extension Functions

Here is a quick overview of the new JavaScript extensions included in this release. A quick look at the source code comments will give you more details on function usage. Eventually, I will get around to converting the documentation comments to online docs. I’ve got to investigate some of the tools that are out there for doing that, though.

String Extensions

String.repeat()
Repeats a character or string a given number of times.

String.prototype.trim()
Trims whitespace from the left and right sides of a string.

String.prototype.leftTrim()
Trims whitespace only from the left side of a string.

String.prototype.rightTrim()
Trims whitespace only from the right side of a string.

String.prototype.leftPad()
Pads the left side of a string with a given character to a given width.

String.prototype.rightPad()
Pads the right side of a string with a given character to a given width.

String.prototype.toFormat()
Takes a source string with value placeholders and replaces the placeholders with actual values.

String.prototype.toNumber()
Converts the string to a number.

Number Extensions

Number.prototype.toFormat()
Converts a number to a formatted string.

Number.prototype.gcd()
Calculates the greatest common divisor between this number and another number.