Skip to content

Instantly share code, notes, and snippets.

@illvart
Forked from cferdinandi/extend.js
Created October 4, 2018 09:46
Show Gist options
  • Save illvart/088c0857ca3972201612acef206ef5d9 to your computer and use it in GitHub Desktop.
Save illvart/088c0857ca3972201612acef206ef5d9 to your computer and use it in GitHub Desktop.
A native JS extend() function.

Example

var defaults = {
    number: 1,
    bool: true,
    magic: 'real',
    animal: 'whale',
    croutons: 'delicious'
};

var options = {
    number: 2,
    magic: 'real',
    animal: 'porpoise',
    bool: false,
    random: 42
};

var settings = extend(defaults, options);

console.log(settings);
// Returns: Object{animal: "porpoise", bool: false, croutons: "delicious", magic: "real", number: 2, random: 42}
/**
* Merge defaults with user options
* @private
* @param {Object} defaults Default settings
* @param {Object} options User options
* @returns {Object} Merged values of defaults and options
*/
var extend = function ( defaults, options ) {
var extended = {};
var prop;
for (prop in defaults) {
if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
extended[prop] = defaults[prop];
}
}
for (prop in options) {
if (Object.prototype.hasOwnProperty.call(options, prop)) {
extended[prop] = options[prop];
}
}
return extended;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment