This snippet extends the date object and provides formatting to short date string. This is usually an issue since JavaScript uses indexes for month. So essentially we create a lookup used for formatting.

// Get the short date dd MMM yyyy
Date.SHORTMONTHNAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
Date.prototype.getShortDateString = function () {
var dateString = this.getDate() + ' ' + Date.SHORTMONTHNAMES[this.getMonth()] + ' ' + this.getFullYear();
return dateString;
};

This snippet extends the document object to provide dictionary type access to the querystring parameters.

Usage:
// http://www.xxx.com?param1=hello
var paramValue = document.getParameterByName('param1');
// paramValue is now 'hello'

 

document.getParameterByName = function (name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
};

This is a handy little string function I use all the time to ellipse strings in a page. Bascially you give it the total length you want and it truncates and adds the ellipses to the end of it. It extends the string class so it is available as a method off the string object.

Usage:

var str = 'This is a really long string';
str = str.ellipse(10);
//str is: 'This is...' total of 10 chars

 

string.prototype.ellipse = function (stringLength) {
  if (this.length > stringLength - 3)
    return this.substring(0, stringLength - 3) + '...';
  else
    return this;
};

With the adoptation of ORM, it is becoming increasingly useful to be able to clone an object graph. This is particualry useful when using the Entity Framework on the POCO model.

This extension method attaches itself to the object class. We use binary serialization to serialize into a memory stream then back out to the target class, essentially making a perfect copy of the object.

This method will also copy any complex object and traverse the entire object graph.

 

public static T DeepClone(this T obj)
{
  using (var ms = new MemoryStream()) {
    var bf = new BinaryFormatter();
    bf.Serialize(ms, obj);
    ms.Position = 0;
    return (T)bf.Deserialize(ms);
  }
}

I am a firm believer of not having wayward functions cluttering up my JavaScript code. Often it is needed to encapsulate these in a globally accessible object. I use this pattern. Note we lean on jQuery to initialize the object when the DOM is ready.

var controller = {
  init: function () {
    controller.wirePageEvents();
  },
  wirePageEvents: function () {
    // Init events
  },
  method1: function () { },
  method2: function () { }
}
$(document).ready(function() {
  controller.init();
});

When presenting a number to the UI, often it is needed in a formatted form. This function extends the number object in JavaScript to provide this functionality.

Usage:

var x = 10000;

var xString = x.toGroupingString(2);
// xString is now: 10, 000.00
// Adds in number grouping and precision
Number.prototype.toGroupingString = function (precision) {
  var nStr = this.toFixed(precision) + '';
  x = nStr.split('.');
  x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
  return x1 + x2;
};

We can add to this to allow presenting ratios as percentages.

// Formats a ration (0.5) as a percent (50%)
Number.prototype.toPercentString = function (precision) {
  var num = this * 100;
  return num.toGroupingString(precision) + '%';
};

I am currently playing around with a small sideline project that has led me into some interesting research regarding loops in JavaScript. As it turns out not all loops are made equal. On analyzing it, it is kind of obvious, but it is something I had never really thought about. It is important to also weigh up the benefit of the performance gain against maintainability. Typically we are talking a couple of milliseconds over several thousand iterations, but for high performance scenarios like canvas painting, every millisecond counts. Also, I will be focusing on the for loop, there are also some while loop variations to consider.

Anatomy of a For Loop

for ([initial-expression]; [condition]; [final-expression]) {
  // statement
}
  • initial-expression get evaluated on initialization of the loop, note this is an expression, and as such can have multiple comma delimited expressions in it.
  • condition is a Boolean condition that gets tested before entering each iteration of the loop
  • final-expression gets evaluated on completion of each iteration but before the next condition is evaluated.

For – In Loop

for (variable in object) {
  // statement
}

The for in loop, designed specifically for associative arrays, but being used quite a lot lately for its readability. Unfortunately it has pretty poor performance.

For Loop

for (i = 0; i < arr.length; i++) {
  // statement
}

The traditional for loop as used by most to iterate through an array. The one downside to this is that the length of the array is evaluated each iteration.

For Loop with Length Caching


var i, iLen;
for (i = 0, iLen = arr.length; i < iLen; i++) {
  // statement
}

This variation of the for loop will cache the length of the array. Syntax is slightly more complicated, but still pretty intuitive. The benefit of this is that the length of the array is not evaluated each iteration.

Decrementing for loop with no Operators


var i, iLen = arr.length;

for (var i=iLen; i--;) {
  // statement
}

This approach does three optimizations. Firstly it caches the length of the array. Secondly, it uses a decrementing counter to iterate through the array, for whatever reason, decrementing in JavaScript appears to be faster than incrementing. Thirdly, it uses the fact that an assignment statement (in this case the decrement) in JavaScript also evaluates to the value of the assignment, additionally, JavaScript evaluates 0, null, undefined and false as false under a boolean context. We therefore do not need to use the comparison operators of >=, <=, >, <, ==. This is faster because boolean operators are polymorphic and need to do type evaluation on the left and right side of the operator before an evaluation can take place. Since we do away with then altogether, we gain this performance.

As a knee jerk reaction we might question if we even enter the loop on the i == 0 case, however it is important to note we are post decrementing (i– instead of –i), which means the decrement takes place after the boolean evaluation. This takes care of the upper and lower edge cases.

Lastly, this method although fast, does not respect the ordering of the array since we are iterating from last to first.

There is an excellent breakdown with timings on Greg Reimer’s blog.