Skip to content

Commit

Permalink
New toQueryString implementation with less recursive functions
Browse files Browse the repository at this point in the history
Conflicts:

	Source/Native/Hash.js
	Specs/Native/Hash.js
  • Loading branch information
anutron committed Jun 10, 2009
1 parent 4c578e5 commit 9931ac9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 20 deletions.
39 changes: 19 additions & 20 deletions Source/Native/Hash.js
Expand Up @@ -107,26 +107,25 @@ Hash.implement({
return values;
},

toQueryString: function(base){
var queryString = [];
Hash.each(this, function(value, key){
if (base) key = base + '[' + key + ']';
var result;
switch ($type(value)){
case 'object': result = Hash.toQueryString(value, key); break;
case 'array':
var qs = {};
value.each(function(val, i){
qs[i] = val;
});
result = Hash.toQueryString(qs, key);
break;
default: result = key + '=' + encodeURIComponent(value);
}
if (value != undefined) queryString.push(result);
});

return queryString.join('&');
toQueryString: function(format){
if($type(format) == 'string') format = { base: format };
format = $extend({ property: '[#]', array: '[#]', separator: '&' }, format);

var queryString = [], base = format.base;
var pushItem = function(value, key){
format.base = base.replace(/\#/, key);
queryString.push(Hash.toQueryString(value, format));
};
if ($type(this).test(/object|hash/)){
base = base ? base + format.property : '#';
Hash.each(this, pushItem);
} else if($type(this) == 'array'){
base = base + format.array;
this.each(pushItem);
} else {
return base + '=' + encodeURIComponent(this);
}
return queryString.join(format.separator);
}

});
Expand Down
14 changes: 14 additions & 0 deletions Specs/Native/Hash.js
Expand Up @@ -196,6 +196,20 @@ describe("Hash Methods", {

var myHash3 = new Hash({fruits: {apple: ['red', 'yellow'], lemon: ['green', 'yellow']}});
value_of(myHash3.toQueryString()).should_be('fruits[apple][0]=red&fruits[apple][1]=yellow&fruits[lemon][0]=green&fruits[lemon][1]=yellow');

value_of(myHash3.toQueryString({ property: '.#', array: '' })).should_be('fruits.apple=red&fruits.apple=yellow&fruits.lemon=green&fruits.lemon=yellow');


var obj = {
first: ['A', 'B'],
second: { a: 1, b: 2 },
third: [{a: 1, b: 2}, {c:3}]
};

value_of(Hash.toQueryString(obj)).should_be('first[0]=A&first[1]=B&second[a]=1&second[b]=2&third[0][a]=1&third[0][b]=2&third[1][c]=3');
value_of(Hash.toQueryString(obj, { property: '.#', array: '[]' })).should_be('first[]=A&first[]=B&second.a=1&second.b=2&third[].a=1&third[].b=2&third[].c=3');
value_of(Hash.toQueryString(obj, { property: '.#', array: '' })).should_be('first=A&first=B&second.a=1&second.b=2&third.a=1&third.b=2&third.c=3');

}

});
Expand Down

0 comments on commit 9931ac9

Please sign in to comment.