Last active
December 29, 2015 12:25
-
-
Save coderofsalvation/8239d9362744896f766c to your computer and use it in GitHub Desktop.
clone and extend in vanilla javascript
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
this.clone = function(obj) { | |
var key, temp; | |
if (obj === null || typeof obj !== 'object' || typeof obj === 'function') return obj; | |
temp = obj.constructor(); | |
for (key in obj) temp[key] = this.clone(obj[key]); | |
return temp; | |
}; | |
this.merge = function(source, obj, clone) { | |
var prop, v; | |
if (source == null) return source; | |
for (prop in obj) { | |
v = obj[prop]; | |
if ((source[prop] != null) && typeof source[prop] === 'object' && typeof obj[prop] === 'object') { | |
this.merge(source[prop], obj[prop]); | |
} else { | |
if (clone) { | |
source[prop] = this.clone; | |
} else { | |
source[prop] = obj[prop]; | |
} | |
} | |
} | |
return source; | |
}; |
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
@clone = (obj) -> | |
key = undefined | |
temp = undefined | |
if obj == null or typeof obj != 'object' or typeof obj == 'function' | |
return obj | |
temp = obj.constructor() | |
for key of obj | |
temp[key] = @clone(obj[key]) | |
temp | |
@merge = (source, obj, clone) -> | |
return source if source == null | |
for prop of obj | |
v = obj[prop] | |
if source[prop] != null and typeof source[prop] == 'object' and typeof obj[prop] == 'object' | |
@merge source[prop], obj[prop] | |
else | |
if clone | |
source[prop] = @clone | |
else | |
source[prop] = obj[prop] | |
source |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment