default-args
Version:
A simple function for providing defaults to an options argument. No dependencies, tiny amount of code.
45 lines (41 loc) • 1.27 kB
JavaScript
/*!
* default-args v1.0.1 (https://github.com/victornpb/default-args)
* Copyright (c) victornpb
* @license MIT
*/
/**
* Returns the options object deeply merged with the defaults.
* Extranous properties are not included in the returned object.
* @param {object} defaults - The object that contains the default values.
* @param {object|undefined|null} [options] - The object to be merged into defaultObj. (it does not mutate this argument)
* @returns {object} the merged object.
*
* @example
* function myFunction(options) {
* options = defaults({
* foo: true,
* bar: {
* a: 1,
* b: 2,
* },
* }, options);
*
* // do stuff with options
* }
*/
function defaultArgs(defaults, options) {
function isObj(x) {
return x !== null && typeof x === 'object';
}
function hasOwn(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
if (isObj(options)) for (var prop in defaults) {
if (hasOwn(defaults, prop) && hasOwn(options, prop) && options[prop] !== undefined) {
if (isObj(defaults[prop])) defaultArgs(defaults[prop], options[prop]);else defaults[prop] = options[prop];
}
}
return defaults;
}
export { defaultArgs as default };
//# sourceMappingURL=default-args.esm.js.map