From b0d942d0ece1ec7bb5bbe8ad54fb87b5db5a96c5 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Mon, 1 Apr 2013 23:49:35 -0700 Subject: [PATCH] Ensure `_.merge` applies a given `callback` to nested properties. [closes #227] Former-commit-id: 1a58c178e0ecb9c50512f221b4aed82762709066 --- lodash.js | 7 +++++-- test/test.js | 11 +++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/lodash.js b/lodash.js index 54d8561ca..ce9b65c56 100644 --- a/lodash.js +++ b/lodash.js @@ -2005,6 +2005,7 @@ var callback = args[3], stackA = args[4], stackB = args[5]; + console.log(object) } else { stackA = []; stackB = []; @@ -2041,9 +2042,10 @@ ? (isArray(value) ? value : []) : (isPlainObject(value) ? value : {}); + var isShallow; if (callback) { result = callback(value, source); - if (typeof result != 'undefined') { + if ((isShallow = typeof result != 'undefined')) { value = result; } } @@ -2052,13 +2054,14 @@ stackB.push(value); // recursively merge objects and arrays (susceptible to call stack limits) - if (!callback) { + if (!isShallow) { value = merge(value, source, indicatorObject, callback, stackA, stackB); } } } else { if (callback) { + console.log('hi') result = callback(value, source); if (typeof result == 'undefined') { result = source; diff --git a/test/test.js b/test/test.js index 42977e53b..b6100971f 100644 --- a/test/test.js +++ b/test/test.js @@ -1801,8 +1801,15 @@ }); test('should handle merging if `callback` returns `undefined`', function() { - var actual = _.merge({ 'a': 1 }, { 'a': 2 }, function() { }); - deepEqual(actual, { 'a': 2 }); + var actual = _.merge({ 'a': { 'b': [1, 1] } }, { 'a': { 'b': [0] } }, function() { }); + deepEqual(actual, { 'a': { 'b': [0, 1] } }); + }); + + test('should defer to `callback` when it returns a value other than `undefined`', function() { + var actual = _.merge({ 'a': { 'b': [0, 1] } }, { 'a': { 'b': [2] } }, function(a, b) { + return _.isArray(a) ? a.concat(b) : undefined; + }); + deepEqual(actual, { 'a': { 'b': [0, 1, 2] } }); }); }(1, 2, 3));