Skip to content

Instantly share code, notes, and snippets.

@jaridmargolin
Last active August 29, 2015 13:57
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 jaridmargolin/9848265 to your computer and use it in GitHub Desktop.
Save jaridmargolin/9848265 to your computer and use it in GitHub Desktop.
Utils - deep extend and deep merge.
define([
'underscore'
], function (_) {
// ----------------------------------------------------------------------------
// utils
// ----------------------------------------------------------------------------
var utils = {};
//
// Same as deepMerge except takes multiple objs.
//
utils.deepExtend = function () {
var args = Array.prototype.slice.call(arguments, 0),
dest = args.shift();
_.each(args, function (val) {
utils.deepMerge(dest, val);
});
return dest;
};
//
// Merge props from obj to dest.
//
utils.deepMerge = function (dest, obj) {
_.each(obj, function (objVal, key) {
var destVal = dest[key] || {};
// Cache info about objVal
var isObj = _.isObject(objVal),
isArr = _.isArray(objVal);
if (isObj || isArr) {
// We need to be working with the same data objects.
// In the case they are different, objVal type will be chosen.
if (isObj && !_.isObject(objVal)) { dest[key] = {}; }
if (isArr && !_.isArray(objVal)) { dest[key] = []; }
dest[key] = utils.deepMerge(destVal, objVal);
} else {
dest[key] = objVal;
}
});
return dest;
};
// ----------------------------------------------------------------------------
// Expose
// ----------------------------------------------------------------------------
return utils;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment