Skip to content

Commit

Permalink
Can now specify always-push behaviour for arrays. Closes TehShrike#14
Browse files Browse the repository at this point in the history
  • Loading branch information
basicallydan committed Aug 9, 2014
1 parent 2d19183 commit d6d7387
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
4 changes: 2 additions & 2 deletions example/merge.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var merge = require('../')
var x = { foo : { 'bar' : 3 } }
var y = { foo : { 'baz' : 4 }, quux : 5 }
var x = { foo : { 'bar' : 3 }, ar : [ { thing : 'b' } ], simplear: [1, 2, 3] }
var y = { foo : { 'baz' : 4 }, quux : 5, ar : [ { thing : 'a' } ], simplear: [4, 5] }
var merged = merge(x, y)
console.dir(merged)
10 changes: 7 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,21 @@
}
}(this, function () {

return function deepmerge(target, src) {
return function deepmerge(target, src, options) {
options = options || { alwaysPush : false };
var array = Array.isArray(src);
var dst = array && [] || {};

if (array) {
console.log('Target:',target);
console.log('Source:',src);
console.log('DST:',src);
target = target || [];
dst = dst.concat(target);
src.forEach(function(e, i) {
if (typeof dst[i] === 'undefined') {
if (typeof dst[i] === 'undefined' && !options.alwaysPush) {
dst[i] = e;
} else if (typeof e === 'object') {
} else if (typeof e === 'object' && !options.alwaysPush) {
dst[i] = deepmerge(target[i], e);
} else {
if (target.indexOf(e) === -1) {
Expand Down
20 changes: 20 additions & 0 deletions test/merge.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,23 @@ test('should work on arrays of nested objects', function(t) {
t.deepEqual(merge(target, src), expected)
t.end()
})

test('should always push onto arrays if specified', function(t) {
var target = [
{ key1: { subkey: 'one' }}
]

var src = [
{ key1: { subkey: 'two' }},
{ key2: { subkey: 'three' }}
]

var expected = [
{ key1: { subkey: 'one' }},
{ key1: { subkey: 'two' }},
{ key2: { subkey: 'three' }}
]

t.deepEqual(merge(target, src, { alwaysPush : true }), expected)
t.end()
})

0 comments on commit d6d7387

Please sign in to comment.