Last active
August 29, 2015 13:57
-
-
Save termi/9809170 to your computer and use it in GitHub Desktop.
deep extend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _hasOwn = Object.prototype.hasOwnProperty; | |
var _toString = Object.prototype.toString; | |
var _hasGOPD = typeof Object.getOwnPropertyDescriptor === 'function'; | |
var _hasDP = typeof Object.defineProperty === 'function'; | |
function _getOwnPropertyDescriptor(obj, prop) { | |
if ( _hasGOPD ) { | |
return Object.getOwnPropertyDescriptor(obj, prop) | |
} | |
else { | |
return { 'value': obj[prop], 'writable': true, 'configurable': true, 'enumerable': true }; | |
} | |
} | |
function _defineProperty(obj, prop, descriptor) { | |
if ( _hasDP ) { | |
Object.defineProperty(obj, prop, descriptor); | |
} | |
else { | |
obj[prop] = descriptor['value']; | |
} | |
} | |
function _deepExtend(target) { | |
for ( var i = 1 ; i < arguments.length ; i++ ) { | |
var donor = arguments[i]; | |
if ( typeof donor == "object" && donor ) { | |
for ( var prop in donor ) if ( _hasOwn.call(donor, prop) ) { | |
var propDesc = _getOwnPropertyDescriptor(donor, prop) | |
, target_propDesc | |
; | |
if ( _toString.call(propDesc.value) == "[object Object]"/* && !(prop in target)*/ ) { | |
target[prop] = _deepExtend({}, donor[prop]); | |
} | |
else if ( _toString.call(propDesc.value) == "[object Array]"/* && !(prop in target)*/ ) { | |
target[prop] = _deepExtend([], donor[prop]); | |
} | |
else if ( !(target_propDesc = _getOwnPropertyDescriptor(target, prop)) | |
|| typeof target_propDesc["value"] !== "object" ) { | |
if ( !target_propDesc | |
|| ( "value" in target_propDesc | |
? target_propDesc["value"] != propDesc["value"] | |
: target_propDesc["get"] !== propDesc["get"] || target_propDesc["set"] !== propDesc["set"] ) | |
&& target_propDesc["configurable"] !== false | |
) { | |
_defineProperty(target, prop, propDesc); | |
} | |
} | |
else { | |
_deepExtend(target[prop], donor[prop]); | |
} | |
}; | |
} | |
} | |
return target; | |
} | |
module.exports = _deepExtend; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment