Thursday, November 18, 2010

Extending the javascript Array object

The ubiquitous javascript Array object. We use it every day, but unfortunately it is missing a few useful things like simple get() and contains() methods. But luckily for us, its easy to extend. Here are a couple simple examples of how to extend the Array object with methods we wish it had by default.

Get Method
Create a simple array of name/value pairs.
Get an array member based on its name.

Array.prototype.get = function(key) {
var i = this.length;
while (i--) { if (this[i].split(":")[0]==key){return this[i].split(":")[1];} }
}

function testGetMethod() {
var opts=["1:one","2:two","3:three","4:four","5:five"];
var item = opts.get("3");
alert(item);
}
//output: three


Contains method
Create a simple array, and see if an item exists in the array.

Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) { if (this[i] === obj){return true;} }
return false;
}

function testContainsMethod() {
var opts=[1,2,3,4,5,10];
if(opts.contains(3)){alert('true');}
}
//output: true


Implementation
Just include the "Array.prototype..." methods somewhere in your page, or a global .js file to make them available to all your pages.

Enjoy!

Wednesday, November 17, 2010

Get a Fully Qualified URL from a Virtual Path

I needed to create a page to handle 404 errors ("Page Not Found"), and automatically redirect them to a related page within the web site. I ran into a little problem when I tried to display the fully qualified URL from a virtual path (all done on the server side in C#). 

With some input from an associate (who suggested I use Url.GetLeftPart), I came up with the following solution:

string fullyQualifiedUrl = GetFullyQualifiedUrl("~/Home");

private string GetFullyQualifiedUrl(string virtualPath)
{
    HttpRequest request = HttpContext.Current.Request;
    string urlLeftPart = request.Url.GetLeftPart(UriPartial.Authority);
    string appPath = request.ApplicationPath;
    string fullyQualifiedUrl = string.Format("{0}{1}{2}", urlLeftPart, appPath, virtualPath).Replace("~/", "");
    return fullyQualifiedUrl;
}


Share & Enjoy!