Skip to content

Commit

Permalink
refactor utils.merge, fixes #45
Browse files Browse the repository at this point in the history
  • Loading branch information
nlf committed Oct 22, 2014
1 parent 5ac9df5 commit 9c69ef4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 29 deletions.
42 changes: 13 additions & 29 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,48 +26,32 @@ exports.merge = function (target, source) {
return target;
}

if (Array.isArray(source)) {
for (var i = 0, il = source.length; i < il; ++i) {
if (typeof source[i] !== 'undefined') {
if (typeof target[i] === 'object') {
target[i] = exports.merge(target[i], source[i]);
}
else {
target[i] = source[i];
}
}
}
if (typeof source !== 'object') {
target.push(source);
return target;
}

if (typeof target !== 'object') {
target = [target].concat(source);
return target;
}

if (Array.isArray(target)) {
if (typeof source !== 'object') {
target.push(source);
return target;
}
else {
target = exports.arrayToObject(target);
}
if (Array.isArray(target) &&
!Array.isArray(source)) {

target = exports.arrayToObject(target);
}

var keys = Object.keys(source);
for (var k = 0, kl = keys.length; k < kl; ++k) {
var key = keys[k];
var value = source[key];

if (value &&
typeof value === 'object') {

if (!target[key]) {
target[key] = value;
}
else {
target[key] = exports.merge(target[key], value);
}
if (!target[key]) {
target[key] = value;
}
else {
target[key] = value;
target[key] = exports.merge(target[key], value);
}
}

Expand Down
11 changes: 11 additions & 0 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,17 @@ describe('parse()', function () {
done();
});

it('parses a mix of simple and explicit arrays', function (done) {

expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] });
done();
});

it('parses a nested array', function (done) {

expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } });
Expand Down

0 comments on commit 9c69ef4

Please sign in to comment.