Created
April 1, 2016 14:30
-
-
Save sanex3339/78fba42ee9597e605c93a744048741e8 to your computer and use it in GitHub Desktop.
Deep Extend underscore typescrpit
This file contains hidden or 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
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