Skip to content

Instantly share code, notes, and snippets.

@Error601
Last active August 29, 2015 14:10
Show Gist options
  • Save Error601/8fdffa6ff985cc374792 to your computer and use it in GitHub Desktop.
Save Error601/8fdffa6ff985cc374792 to your computer and use it in GitHub Desktop.
jQuery's 'extend' method without the rest of jQuery
/*!
* Native JS version of jQuery's $.extend() method
* (code lifted from jQuery 1.11.1 and slightly modified)
* native JS implementations of $.isPlainObject(), $.isArray(), $.isFunction()
* https://gist.github.com/Error601/8fdffa6ff985cc374792
*/
function extend(){
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
function isPlainObject (obj){
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isArray (arr){
if ( Array.isArray ) {
return Array.isArray(arr);
}
else {
return Object.prototype.toString.call(arr) === '[object Array]';
}
}
function isFunction (func){
return typeof func == 'function';
}
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !isFunction(target) ) {
target = {};
}
// extend parent object if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
// 'for' loops blow
while ( i < length ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
if ( !options.hasOwnProperty(name) ) {
continue;
}
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
}
else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = extend(deep, clone, copy);
// Don't bring in undefined values
}
else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
i++;
}
// Return the modified object
return target;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment