Archive for November, 2010

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;
};
Advertisements

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) + '%';
};