Permalink
Browse files

fix possibility to create huge sparse arrays.

  • Loading branch information...
1 parent 1e39ad7 commit c7b9562575a542e0285deb6adca7d100fba54cf3 @abecciu abecciu committed with Apr 30, 2013
Showing with 32 additions and 2 deletions.
  1. +26 −2 index.js
  2. +6 −0 test/parse.js
View
@@ -142,6 +142,27 @@ function merge(parent, key, val){
}
/**
+ * Compact sparse arrays
+ */
+
+function compact(obj) {
+ if ('object' != typeof obj) return obj;
+
+ if (isArray(obj)) {
+ var ret = [];
+ for (var i in obj) ret.push(obj[i]);
+ return ret;
+ }
+
+ for (var key in obj) {
+ obj[key] = compact(obj[key]);
+ }
+
+ return obj;
+}
+
+
+/**
* Parse the given obj.
*/
@@ -150,15 +171,16 @@ function parseObject(obj){
forEach(objectKeys(obj), function(name){
merge(ret, name, obj[name]);
});
- return ret.base;
+
+ return compact(ret.base);
}
/**
* Parse the given str.
*/
function parseString(str){
- return reduce(String(str).split('&'), function(ret, pair){
+ var ret = reduce(String(str).split('&'), function(ret, pair){
var eql = indexOf(pair, '=')
, brace = lastBraceInKey(pair)
, key = pair.substr(0, brace || eql)
@@ -171,6 +193,8 @@ function parseString(str){
return merge(ret, decode(key), decode(val));
}, { base: createObject() }).base;
+
+ return compact(ret);
}
/**
View
@@ -150,6 +150,12 @@ describe('qs.parse()', function(){
.to.eql({ _r: '1' })
})
+ it('should not create big arrays of null objects', function(){
+ var q = qs.parse('a[999999999]=1&a[2]=2');
+ expect(q['a'].length).to.eql(2);
+ expect(q).to.eql({ a: ['2', '1'] });
+ })
+
if ('undefined' == typeof window) {
it('should not be possible to access Object prototype', function() {
qs.parse('constructor[prototype][bad]=bad');

0 comments on commit c7b9562

Please sign in to comment.