Created
August 20, 2014 18:15
-
-
Save goliatone/6682785b1ba1eff10040 to your computer and use it in GitHub Desktop.
merge only an object's properties into target that are defined in a given array.
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
define('helpers/merge', function() { | |
/** | |
* Extend method. Deep cloning. | |
* @param {Object} target Object to be extended. | |
* @return {Object} Extended object. | |
*/ | |
var _merge = function merge(target, attributes) { | |
var sources = [].slice.call(arguments, 2); | |
var skip = buildCheck(attributes); | |
sources.forEach(function(source) { | |
for (var property in source) { | |
if (skip(property)) continue; | |
if (source[property] && source[property].constructor && | |
source[property].constructor === Object) { | |
target[property] = target[property] || {}; | |
target[property] = merge(target[property], source[property]); | |
} else target[property] = source[property]; | |
} | |
}); | |
return target; | |
}; | |
function buildCheck(attributes) { | |
if (typeof attributes === 'function') return attributes; | |
if (Array.isArray(attributes)) { | |
return function(attribute) { | |
return attributes.indexOf(attribute) === -1; | |
} | |
} | |
if (typeof attributes === 'boolean') return function(attribute) { | |
return !attributes; | |
} | |
if (!attributes) return function(attribute) { | |
return false; | |
} | |
} | |
return _merge; | |
}); | |
/* | |
* Shim dependency. | |
*/ | |
if (!Array.isArray) { | |
Array.isArray = function(arg) { | |
return Object.prototype.toString.call(arg) === '[object Array]'; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment