Last active
August 29, 2015 13:57
-
-
Save jaridmargolin/9848265 to your computer and use it in GitHub Desktop.
Utils - deep extend and deep merge.
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
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