Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 5e927ee

Browse files
prettycodecaitp
authored andcommitted
feat(extend): optionally deep-extend when last parameter is true
1 parent ae637ac commit 5e927ee

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/Angular.js

+13-3
Original file line numberDiff line numberDiff line change
@@ -333,22 +333,32 @@ function setHashKey(obj, h) {
333333
* Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
334334
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
335335
* by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
336-
* Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).
336+
* Note: Pass `true` in as the last argument to perform a recursive merge (deep copy).
337337
*
338338
* @param {Object} dst Destination object.
339339
* @param {...Object} src Source object(s).
340340
* @returns {Object} Reference to `dst`.
341341
*/
342342
function extend(dst) {
343343
var h = dst.$$hashKey;
344+
var argsLength = arguments.length;
345+
var isDeep = (argsLength >= 3) && (arguments[argsLength - 1] === true);
344346

345-
for (var i = 1, ii = arguments.length; i < ii; i++) {
347+
if (isDeep) --argsLength;
348+
349+
for (var i = 1; i < argsLength; i++) {
346350
var obj = arguments[i];
347351
if (obj) {
348352
var keys = Object.keys(obj);
349353
for (var j = 0, jj = keys.length; j < jj; j++) {
350354
var key = keys[j];
351-
dst[key] = obj[key];
355+
var src = obj[key];
356+
357+
if (isDeep && isObject(dst[key])) {
358+
src = extend(dst[key], src, true);
359+
}
360+
361+
dst[key] = src;
352362
}
353363
}
354364
}

test/AngularSpec.js

+15
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,21 @@ describe('angular', function() {
223223
// make sure we retain the old key
224224
expect(hashKey(dst)).toEqual(h);
225225
});
226+
227+
it('should perform deep extend when last argument is true', function() {
228+
var src = { foo: { bar: 'foobar', age: 10, nothing: null, undef: void 0 }},
229+
dst = { foo: { bazz: 'foobazz' }};
230+
extend(dst, src, true);
231+
expect(dst).toEqual({
232+
foo: {
233+
bar: 'foobar',
234+
bazz: 'foobazz',
235+
age: 10,
236+
nothing: null,
237+
undef: void 0
238+
}
239+
});
240+
});
226241
});
227242

228243
describe('shallow copy', function() {

0 commit comments

Comments
 (0)