Skip to content

Instantly share code, notes, and snippets.

@jiggliemon
Created June 2, 2011 23:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiggliemon/1005605 to your computer and use it in GitHub Desktop.
Save jiggliemon/1005605 to your computer and use it in GitHub Desktop.
A General use Hash object with some helper methods.
;(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