UNPKG

super-utils-plus

Version:

A superior alternative to Lodash with improved performance, TypeScript support, and developer experience

86 lines (85 loc) 2.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaults = defaults; exports.defaultsDeep = defaultsDeep; const is_1 = require("../utils/is"); /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to undefined. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * @param object - The destination object * @param sources - The source objects * @returns The destination object * * @example * ```ts * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } * ``` */ function defaults(object, ...sources) { if (!(0, is_1.isObject)(object)) { return object; } const result = { ...object }; for (const source of sources) { if ((0, is_1.isObject)(source)) { for (const key in source) { if (result[key] === undefined) { result[key] = source[key]; } } } } return result; } /** * This method is like defaults except that it recursively assigns * default properties. * * @param object - The destination object * @param sources - The source objects * @returns The destination object * * @example * ```ts * defaults({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } * ``` */ function defaultsDeep(object, ...sources) { if (!(0, is_1.isObject)(object)) { return object; } const result = { ...object }; for (const source of sources) { if ((0, is_1.isObject)(source)) { recursiveDefaults(result, source); } } return result; } /** * Helper function for recursive defaults assignment. */ function recursiveDefaults(object, source) { for (const key in source) { const objValue = object[key]; const srcValue = source[key]; // Skip non-own properties if (!Object.prototype.hasOwnProperty.call(source, key)) { continue; } // If property doesn't exist in object, assign it if ((0, is_1.isNil)(objValue)) { object[key] = srcValue; } // If both are objects, recurse else if ((0, is_1.isObject)(objValue) && (0, is_1.isObject)(srcValue)) { recursiveDefaults(objValue, srcValue); } // Otherwise keep the existing value } }