Chad Scharf's Weblog
It's always time to upgrade!

Creating a JavaScript HashTable

Friday, 2 May 2008 16:10 by Chad

I use a lot of configuration and provider driven services and variables for developing web applications. Let's face it, I don't like to recompile. I recently had the need to share my Web.config settings with the client code, but didn't want to declare a variable for every possible setting, I just wanted to dynamically create the script of configuration settings in some collection and have access to that in my client side code. Because I wanted this collection to act just like a HashTable in System.Collections, I decided to create a JavaScript type to mirror the storage and access paradigm of the HashTable for use in my applications. More...

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Shrinking JavaScript Arrays

Friday, 11 April 2008 20:21 by Chad

Recently I've found myself writing a ton of client code in a new pure JavaScript/WCF project I am working on. Since most of the programming I'm doing for the UI is in JavaScript files, I've found myself having to work with the Array object for many different things. The one thing I've noticed however, is that you cannot remove an item from a JavaScript array, say, in the middle of the array and have the array size shrink without losing data at either end, however having to check for array_name[i] != null every single time I iterate the array was getting annoying, to say the least.

I decided to flex the muscle of the prototype, which in JavaScript allows you to extend a types method and properties. This new method I created, called shrink(), aptly removes all of the nulls from my array and shrinks the total length without losing any data. I'm not sure how efficient it is, but it works and I no longer have to check for null where at least it doesn't make sense to anyway.

Array.prototype.shrink = function() {
    var sync = new Array();
    while (this.length > 0) {
        var obj = this.shift();
        if (obj !== null) sync.push(obj);
    }
    while (sync.length > 0) {
        var obj = sync.shift();
        if (obj !== null) this.push(obj);
    }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:  
Categories:   The Client Side
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed