Created
June 2, 2011 23:57
-
-
Save jiggliemon/1005605 to your computer and use it in GitHub Desktop.
A General use Hash object with some helper methods.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function(global,namespace){ | |
if(!namespace) namespace = global; | |
/* | |
--- | |
name: Hash | |
authors: ["Chase Wilson"] | |
requires: [typeOf] | |
provides: [Hash] | |
... | |
*/ | |
var Hash = namespace.Hash = function(options){ | |
this.initialize(options); | |
}; | |
Hash.prototype.initialize = function(options){ | |
this.hash = {}; | |
}; | |
Hash.prototype.toQueryString = function(obj,base){ | |
var queryString = [] | |
,self = this | |
,key | |
,obj = (obj) ? obj : (this.hash) ? this.hash: false; | |
// if we don't have an object to create a query off of we need to throw an error. | |
if(!obj) throw new Error(this.errors['toQueryString.param']); | |
for(key in obj){ | |
if(obj.hasOwnProperty(key)){ | |
if (base) key = base + '[' + key + ']'; | |
var result; | |
switch (namespace.typeOf(obj[key])){ | |
case 'object': | |
result = self.toQueryString(object[key], key); | |
break; | |
case 'array': | |
var qs = {} | |
,nested = obj[key] | |
,i; | |
for(i in nested){ | |
if(nested.hasOwnProperty(i)){ | |
qs[i] = nested[i]; | |
} | |
} | |
result = Hash.toQueryString(qs, key); | |
break; | |
default: | |
result = key + '=' + encodeURIComponent(obj[key]); | |
} | |
if (obj[key] != null) queryString.push(result); | |
} | |
} | |
return queryString.join('&'); | |
}; | |
Hash.toQueryString = Hash.prototype.toQueryString; | |
Hash.errors = { | |
"toQueryString.param":"Hash `toQueryString` requires an Object as the first argument." | |
} | |
})(global || window, namespace); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment