Skip to content

Instantly share code, notes, and snippets.

@sanex3339
Created April 1, 2016 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanex3339/78fba42ee9597e605c93a744048741e8 to your computer and use it in GitHub Desktop.
Save sanex3339/78fba42ee9597e605c93a744048741e8 to your computer and use it in GitHub Desktop.
Deep Extend underscore typescrpit
import * as _ from "underscore";
/**
* @param destination
* @param sources
* @returns {any}
* @constructor
*/
export function DeepExtend (destination: any, ...sources: any[]): any {
var parentRE: RegExp = new RegExp('#{\s*?_\s*?}');
_.each(sources, function(source: any) {
for (let prop in source) {
if (!source.hasOwnProperty(prop)) {
continue;
}
if (_.isUndefined(destination[prop]) || _.isFunction(destination[prop]) || _.isNull(source[prop]) || _.isDate(source[prop])) {
destination[prop] = source[prop];
} else if (_.isString(source[prop]) && parentRE.test(source[prop])) {
if (_.isString(destination[prop])) {
destination[prop] = source[prop].replace(parentRE, destination[prop]);
}
} else if (_.isArray(destination[prop]) || _.isArray(source[prop])){
if (!_.isArray(destination[prop]) || !_.isArray(source[prop])){
throw new Error('Trying to combine an array with a non-array (' + prop + ')');
} else {
destination[prop] = _.reject(DeepExtend(_.clone(destination[prop]), source[prop]), function (item) { return _.isNull(item);});
}
} else if (_.isObject(destination[prop]) || _.isObject(source[prop])){
if (!_.isObject(destination[prop]) || !_.isObject(source[prop])){
throw new Error('Trying to combine an object with a non-object (' + prop + ')');
} else {
destination[prop] = DeepExtend(_.clone(destination[prop]), source[prop]);
}
} else {
destination[prop] = source[prop];
}
}
});
return destination;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment